Flask框架(1)-程序基本結構

1. 安裝Flask

1.1 安裝虛擬環境html

mkdir myproject
cd myproject
py -3 -m venv venv
#Linux系統: python3 -m venv venv

 1.2 激活虛擬環境python

venv\Scripts\activate
#Linux中: . venv/bin/activate

 1.3 安裝Flask數據庫

(venv) D:\Tmp\myproject>pip install Flask
2. 第一個Flask程序
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello world'

if __name__ == '__main__':
    app.run()

 

初始化:app = Flask(__name__)flask

  Flask類只須要有個構造參數即主模塊或包的名字,這個參數決定程序的根目錄,以便找到相對於根目錄的資源文件,這個大部分狀況__name__就是所須要的值。api

 路由:@app.route('/')安全

  處理函數和和URL的關係,Flask經過修飾器把函數註冊爲路由。訪問http://localhost:5000就會調用index這個視圖函數  cookie

訪問:http://127.0.0.1:5000,頁面便可獲得hello world.app

 

 默認只能本機訪問,能夠修改端口和容許的主機:app.run(host = '0.0.0.0',port = 7777,debug = True )函數

 3.上下文

   Flask有程序上下文和請求兩種上下文,Flask使用上下文把一些對象設置爲在一個線程內全局可訪問。this

Flask在分發請求以前,激活或者說推送程序和請求上下文,請求處理完後進行刪除。注意必定要激活纔可使用上下文。

4. 請求調度

   查看URL和處理函數的映射關係:

  這裏有一個特殊的映射關係/static/<filename>,這是Flask添加的特殊路由,用於訪問靜態文件。url_for('static', username='js/test.js')

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}\'s profile'.format(username)

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

/
/login
/login?next=/
/user/John%20Doe
5. 請求鉤子

   鉤子用於處理請求以前或者以後,好比說請求開始前創建數據庫鏈接,Flask支持下面四種鉤子:

6. 響應

6.1 響應狀態碼

@app.route('/')
def index():
    return '<h1>Hello World!</h1>',400

 

6.2  返回respones對象

@app.route('/')
def index():
    response = app.make_response('<h1>This document carries a cookie</h1>')
    response.set_cookie('name', 'scott')
    return response

 

6.3 重定向

from flask import redirect
app = Flask(__name__)

@app.route('/')
def red():
    return redirect('https://www.baidu.com')

 

6.4 abort函數處理錯誤

@app.route('/login')
def login():
    abort(401)
    this_is_never_executed() 
7. 渲染模板

從Python內部生成HTML並很差玩,並且實際上很是麻煩,由於您必須自行執行HTML轉義以保持應用程序的安全。由於Flask 自動爲你配置Jinja2模板引擎。

要呈現模板,您可使用該render_template() 方法。您所要作的就是提供模板的名稱以及想要做爲關鍵字參數傳遞給模板引擎的變量。如下是如何呈現模板的簡單示例:

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

 

8. HTTP方法

根據不一樣的請求方法,執行不一樣的方法。

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()
9. request
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)

 

要訪問在URL(?key=value)中提交的參數,您可使用 args屬性:

searchword = request.args.get('key', '')
10. 文件上傳 
from flask import request
from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        #儘量以原名字命名,中文會被去掉
        f.save('/var/www/uploads/' + secure_filename(f.filename))  
相關文章
相關標籤/搜索