溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python如何使用Web框架Flask開發(fā)項(xiàng)目

發(fā)布時(shí)間:2022-06-01 09:26:30 來源:億速云 閱讀:138 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Python如何使用Web框架Flask開發(fā)項(xiàng)目”,在日常操作中,相信很多人在Python如何使用Web框架Flask開發(fā)項(xiàng)目問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Python如何使用Web框架Flask開發(fā)項(xiàng)目”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

一、簡(jiǎn)介

Flask是一個(gè)輕量級(jí)的基于Python的web框架。

這份文檔中的代碼使用 Python 3 運(yùn)行。 
建議在 linux 下實(shí)踐本教程中命令行操作、執(zhí)行代碼。

二、安裝

通過pip3安裝Flask即可:

$ sudo pip3 install Flask

進(jìn)入python交互模式看下Flask的介紹和版本:

$ python3
 
>>> import flask
>>> print(flask.__doc__)
 
    flask
    ~~~~~
 
    A microframework based on Werkzeug.  It's extensively documented
    and follows best practice patterns.
 
    :copyright: ? 2010 by the Pallets team.
    :license: BSD, see LICENSE for more details.
 
>>> print(flask.__version__)
1.0.2

三、從 Hello World 開始

本節(jié)主要內(nèi)容:使用Flask寫一個(gè)顯示”Hello World!”的web程序,如何配置、調(diào)試Flask。

3.1 Hello World

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

statictemplates目錄是默認(rèn)配置,其中static用來存放靜態(tài)資源,例如圖片、js、css文件等。templates存放模板文件。 
我們的網(wǎng)站邏輯基本在server.py文件中,當(dāng)然,也可以給這個(gè)文件起其他的名字。

在server.py中加入以下內(nèi)容:

from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
if __name__ == '__main__':
    app.run()

運(yùn)行server.py:

$ python3 server.py 
 * Running on http://127.0.0.1:5000/

打開瀏覽器訪問http://127.0.0.1:5000/,瀏覽頁面上將出現(xiàn)Hello World!。 
終端里會(huì)顯示下面的信息:

127.0.0.1 - - [16/May/2014 10:29:08] "GET / HTTP/1.1" 200 -

變量app是一個(gè)Flask實(shí)例,通過下面的方式:

@app.route('/')
def hello_world():
    return 'Hello World!'

當(dāng)客戶端訪問/時(shí),將響應(yīng)hello_world()函數(shù)返回的內(nèi)容。注意,這不是返回Hello World!這么簡(jiǎn)單,Hello World!只是HTTP響應(yīng)報(bào)文的實(shí)體部分,狀態(tài)碼等信息既可以由Flask自動(dòng)處理,也可以通過編程來制定。

3.2 修改Flask的配置

app = Flask(__name__)

上面的代碼中,python內(nèi)置變量__name__的值是字符串__main__ 。Flask類將這個(gè)參數(shù)作為程序名稱。當(dāng)然這個(gè)是可以自定義的,比如app = Flask("my-app")。

Flask默認(rèn)使用static目錄存放靜態(tài)資源,templates目錄存放模板,這是可以通過設(shè)置參數(shù)更改的:

app = Flask("my-app", static_folder="path2", template_folder="path3")

更多參數(shù)請(qǐng)參考__doc__

from flask import Flask
print(Flask.__doc__)

3.3 調(diào)試模式

上面的server.py中以app.run()方式運(yùn)行,這種方式下,如果服務(wù)器端出現(xiàn)錯(cuò)誤是不會(huì)在客戶端顯示的。但是在開發(fā)環(huán)境中,顯示錯(cuò)誤信息是很有必要的,要顯示錯(cuò)誤信息,應(yīng)該以下面的方式運(yùn)行Flask:

app.run(debug=True)

debug設(shè)置為True的另一個(gè)好處是,程序啟動(dòng)后,會(huì)自動(dòng)檢測(cè)源碼是否發(fā)生變化,若有變化則自動(dòng)重啟程序。這可以幫我們省下很多時(shí)間。

3.4 綁定IP和端口

默認(rèn)情況下,F(xiàn)lask綁定IP為127.0.0.1,端口為5000。我們也可以通過下面的方式自定義:

app.run(host='0.0.0.0', port=80, debug=True)

0.0.0.0代表電腦所有的IP。80是HTTP網(wǎng)站服務(wù)的默認(rèn)端口。什么是默認(rèn)?比如,我們?cè)L問網(wǎng)站http://www.example.com,其實(shí)是訪問的http://www.example.com:80,只不過:80可以省略不寫。

由于綁定了80端口,需要使用root權(quán)限運(yùn)行server.py。也就是:

$ sudo python3 server.py

四、獲取 URL 參數(shù)

URL參數(shù)是出現(xiàn)在url中的鍵值對(duì),例如http://127.0.0.1:5000/?disp=3中的url參數(shù)是{'disp':3}。

4.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

4.2 列出所有的url參數(shù)

在server.py中添加以下內(nèi)容:

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return request.args.__str__()
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

在瀏覽器中訪問http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,將顯示:

ImmutableMultiDict([('user', 'Flask'), ('time', ''), ('p', '7'), ('p', '8')])

較新的瀏覽器也支持直接在url中輸入中文(最新的火狐瀏覽器內(nèi)部會(huì)幫忙將中文轉(zhuǎn)換成符合URL規(guī)范的數(shù)據(jù)),在瀏覽器中訪問http://127.0.0.1:5000/?info=這是愛,,將顯示:

ImmutableMultiDict([('info', '這是愛,')])

瀏覽器傳給我們的Flask服務(wù)的數(shù)據(jù)長什么樣子呢?可以通過request.full_pathrequest.path來看一下:

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    print(request.path)
    print(request.full_path)
    return request.args.__str__()
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

瀏覽器訪問http://127.0.0.1:5000/?info=這是愛,,運(yùn)行server.py的終端會(huì)輸出: 
1./

2./?info=%E8%BF%99%E6%98%AF%E7%88%B1%EF%BC%8C

4.3 獲取某個(gè)指定的參數(shù)

例如,要獲取鍵info對(duì)應(yīng)的值,如下修改server.py:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return request.args.get('info')
 
if __name__ == '__main__':
    app.run(port=5000)

運(yùn)行server.py,在瀏覽器中訪問http://127.0.0.1:5000/?info=hello,瀏覽器將顯示:

hello

不過,當(dāng)我們?cè)L問http://127.0.0.1:5000/時(shí)候卻出現(xiàn)了500錯(cuò)誤

為什么為這樣?

這是因?yàn)闆]有在URL參數(shù)中找到info。所以request.args.get('info')返回Python內(nèi)置的None,而Flask不允許返回None。

解決方法很簡(jiǎn)單,我們先判斷下它是不是None:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    r = request.args.get('info')
    if r==None:
        # do something
        return ''
    return r
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

另外一個(gè)方法是,設(shè)置默認(rèn)值,也就是取不到數(shù)據(jù)時(shí)用這個(gè)值:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    r = request.args.get('info', 'hi')
    return r
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

函數(shù)request.args.get的第二個(gè)參數(shù)用來設(shè)置默認(rèn)值。此時(shí)在瀏覽器訪問http://127.0.0.1:5000/,將顯示:

hi

4.4 如何處理多值

還記得上面有一次請(qǐng)求是這樣的嗎? http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,仔細(xì)看下,p有兩個(gè)值。

如果我們的代碼是:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    r = request.args.get('p')
    return r
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

在瀏覽器中請(qǐng)求時(shí),我們只會(huì)看到7。如果我們需要把p的所有值都獲取到,該怎么辦?

不用get,用getlist

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    r = request.args.getlist('p')  # 返回一個(gè)list
    return str(r)
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

瀏覽器輸入 http://127.0.0.1:5000/?user=Flask&time&p=7&p=8,我們會(huì)看到['7', '8']。

五、獲取POST方法傳送的數(shù)據(jù)

作為一種HTTP請(qǐng)求方法,POST用于向指定的資源提交要被處理的數(shù)據(jù)。我們?cè)谀尘W(wǎng)站注冊(cè)用戶、寫文章等時(shí)候,需要將數(shù)據(jù)傳遞到網(wǎng)站服務(wù)器中。并不適合將數(shù)據(jù)放到URL參數(shù)中,密碼放到URL參數(shù)中容易被看到,文章數(shù)據(jù)又太多,瀏覽器不一定支持太長長度的URL。這時(shí),一般使用POST方法。

本文使用python的requests庫模擬瀏覽器。

安裝方法:

$ sudo pip3 install requests

5.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

5.2 查看POST數(shù)據(jù)內(nèi)容

以用戶注冊(cè)為例子,我們需要向服務(wù)器/register傳送用戶名name和密碼password。如下編寫HelloWorld/server.py。

from flask import Flask, request
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/register', methods=['POST'])
def register():
    print(request.headers)
    print(request.stream.read())
    return 'welcome'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

`@app.route(‘/register’, methods=[‘POST’])是指url/register只接受POST方法??梢愿鶕?jù)需要修改methods`參數(shù),例如如果想要讓它同時(shí)支持GET和POST,這樣寫:

@app.route('/register', methods=['GET', 'POST'])

瀏覽器模擬工具client.py內(nèi)容如下:

import requests
 
user_info = {'name': 'letian', 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
 
print(r.text)

運(yùn)行HelloWorld/server.py,然后運(yùn)行client.py。client.py將輸出:

welcome

而HelloWorld/server.py在終端中輸出以下調(diào)試信息(通過print輸出):

Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
 
 
b'name=letian&password=123'

前6行是client.py生成的HTTP請(qǐng)求頭,由print(request.headers)輸出。

請(qǐng)求體的數(shù)據(jù),我們通過print(request.stream.read())輸出,結(jié)果是:

b'name=letian&password=123'

5.3 解析POST數(shù)據(jù)

上面,我們看到post的數(shù)據(jù)內(nèi)容是:

b'name=letian&password=123'

我們要想辦法把我們要的name、password提取出來,怎么做呢?自己寫?不用,F(xiàn)lask已經(jīng)內(nèi)置了解析器request.form。

我們將服務(wù)代碼改成:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/register', methods=['POST'])
def register():
    print(request.headers)
    # print(request.stream.read()) # 不要用,否則下面的form取不到數(shù)據(jù)
    print(request.form)
    print(request.form['name'])
    print(request.form.get('name'))
    print(request.form.getlist('name'))
    print(request.form.get('nickname', default='little apple'))
    return 'welcome'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

執(zhí)行client.py請(qǐng)求數(shù)據(jù),服務(wù)器代碼會(huì)在終端輸出:

Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
 
 
ImmutableMultiDict([('name', 'letian'), ('password', '123')])
letian
letian
['letian']
little apple

request.form會(huì)自動(dòng)解析數(shù)據(jù)。

request.form['name']request.form.get('name')都可以獲取name對(duì)應(yīng)的值。對(duì)于request.form.get()可以為參數(shù)default指定值以作為默認(rèn)值。所以:

print(request.form.get('nickname', default='little apple'))

輸出的是默認(rèn)值

little apple

如果name有多個(gè)值,可以使用request.form.getlist('name'),該方法將返回一個(gè)列表。我們將client.py改一下:

import requests
 
user_info = {'name': ['letian', 'letian2'], 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
 
print(r.text)

此時(shí)運(yùn)行client.py,print(request.form.getlist('name'))將輸出:

[u'letian', u'letian2']

六、處理和響應(yīng)JSON數(shù)據(jù)

使用 HTTP POST 方法傳到網(wǎng)站服務(wù)器的數(shù)據(jù)格式可以有很多種,比如「5. 獲取POST方法傳送的數(shù)據(jù)」講到的name=letian&password=123這種用過&符號(hào)分割的key-value鍵值對(duì)格式。我們也可以用JSON格式、XML格式。相比XML的重量、規(guī)范繁瑣,JSON顯得非常小巧和易用。

6.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

6.2 處理JSON格式的請(qǐng)求數(shù)據(jù)

如果POST的數(shù)據(jù)是JSON格式,request.json會(huì)自動(dòng)將json數(shù)據(jù)轉(zhuǎn)換成Python類型(字典或者列表)。

編寫server.py:

from flask import Flask, request
 
app = Flask("my-app")
 
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
 
@app.route('/add', methods=['POST'])
def add():
    print(request.headers)
    print(type(request.json))
    print(request.json)
    result = request.json['a'] + request.json['b']
    return str(result)
 
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)

編寫client.py模擬瀏覽器請(qǐng)求:

import requests
 
json_data = {'a': 1, 'b': 2}
 
r = requests.post("http://127.0.0.1:5000/add", json=json_data)
 
print(r.text)

運(yùn)行server.py,然后運(yùn)行client.py,client.py 會(huì)在終端輸出:

3

server.py 會(huì)在終端輸出:

Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 16
Content-Type: application/json
 
 

{'a': 1, 'b': 2}

注意,請(qǐng)求頭中Content-Type的值是application/json。

6.3 響應(yīng)JSON-方案1

響應(yīng)JSON時(shí),除了要把響應(yīng)體改成JSON格式,響應(yīng)頭的Content-Type也要設(shè)置為application/json。

編寫server2.py:

from flask import Flask, request, Response
import json
 
app = Flask("my-app")
 
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
 
@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    return Response(json.dumps(result),  mimetype='application/json')
 
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)

修改后運(yùn)行。

編寫client2.py:

import requests
 
json_data = {'a': 1, 'b': 2}
 
r = requests.post("http://127.0.0.1:5000/add", json=json_data)
 
print(r.headers)
print(r.text)

運(yùn)行client.py,將顯示:

{'Content-Type': 'application/json', 'Content-Length': '10', 'Server': 'Werkzeug/0.14.1 Python/3.6.4', 'Date': 'Sat, 07 Jul 2018 05:23:00 GMT'}

{"sum": 3}

上面第一段內(nèi)容是服務(wù)器的響應(yīng)頭,第二段內(nèi)容是響應(yīng)體,也就是服務(wù)器返回的JSON格式數(shù)據(jù)。

另外,如果需要服務(wù)器的HTTP響應(yīng)頭具有更好的可定制性,比如自定義Server,可以如下修改add()函數(shù):

@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    resp = Response(json.dumps(result),  mimetype='application/json')
    resp.headers.add('Server', 'python flask')
    return resp

client2.py運(yùn)行后會(huì)輸出:

{'Content-Type': 'application/json', 'Content-Length': '10', 'Server': 'python flask', 'Date': 'Sat, 07 Jul 2018 05:26:40 GMT'}

{"sum": 3}

6.4 響應(yīng)JSON-方案2

使用 jsonify 工具函數(shù)即可。

from flask import Flask, request, jsonify
 
app = Flask("my-app")
 
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
 
@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    return jsonify(result)
 
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)

七、上傳文件

上傳文件,一般也是用POST方法。

7.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

7.2 上傳文件

這一部分的代碼參考自How to upload a file to the server in Flask。

我們以上傳圖片為例: 
假設(shè)將上傳的圖片只允許’png’、’jpg’、’jpeg’、’gif’這四種格式,通過url/upload使用POST上傳,上傳的圖片存放在服務(wù)器端的static/uploads目錄下。

首先在項(xiàng)目HelloWorld中創(chuàng)建目錄static/uploads

mkdir HelloWorld/static/uploads

werkzeug庫可以判斷文件名是否安全,例如防止文件名是../../../a.png,安裝這個(gè)庫:

$ sudo pip3 install werkzeug

server.py代碼:

from flask import Flask, request
 
from werkzeug.utils import secure_filename
import os
 
app = Flask(__name__)
 
# 文件上傳目錄
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
# 支持的文件格式
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}  # 集合類型
 
 
# 判斷文件名是否是我們支持的格式
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/upload', methods=['POST'])
def upload():
    upload_file = request.files['image']
    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        # 將文件保存到 static/uploads 目錄,文件名同上傳時(shí)使用的文件名
        upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
        return 'info is '+request.form.get('info', '')+'. success'
    else:
        return 'failed'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

app.config中的config是字典的子類,可以用來設(shè)置自有的配置信息,也可以設(shè)置自己的配置信息。函數(shù)allowed_file(filename)用來判斷filename是否有后綴以及后綴是否在app.config['ALLOWED_EXTENSIONS']中。

客戶端上傳的圖片必須以image01標(biāo)識(shí)。upload_file是上傳文件對(duì)應(yīng)的對(duì)象。app.root_path獲取server.py所在目錄在文件系統(tǒng)中的絕對(duì)路徑。upload_file.save(path)用來將upload_file保存在服務(wù)器的文件系統(tǒng)中,參數(shù)最好是絕對(duì)路徑,否則會(huì)報(bào)錯(cuò)(網(wǎng)上很多代碼都是使用相對(duì)路徑,但是筆者在使用相對(duì)路徑時(shí)總是報(bào)錯(cuò),說找不到路徑)。函數(shù)os.path.join()用來將使用合適的路徑分隔符將路徑組合起來。

好了,定制客戶端client.py:

import requests
file_data = {'image': open('Lenna.jpg', 'rb')}
user_info = {'info': 'Lenna'}
r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=file_data)
print(r.text)

運(yùn)行client.py,當(dāng)前目錄下的Lenna.jpg將上傳到服務(wù)器。

然后,我們可以在static/uploads中看到文件Lenna.jpg。

要控制上產(chǎn)文件的大小,可以設(shè)置請(qǐng)求實(shí)體的大小,例如:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB

不過,在處理上傳文件時(shí)候,需要使用try:...except:...。

如果要獲取上傳文件的內(nèi)容可以:

file_content = request.files['image'].stream.read()

八、Restful URL

簡(jiǎn)單來說,Restful URL可以看做是對(duì) URL 參數(shù)的替代。

8.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

8.2 編寫代碼

編輯server.py:

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user/')
def user(username):
    print(username)
    print(type(username))
    return 'hello ' + username
 
 
@app.route('/user//friends')
def user_friends(username):
    print(username)
    print(type(username))

    return 'hello ' + username
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

運(yùn)行HelloWorld/server.py。使用瀏覽器訪問http://127.0.0.1:5000/user/letian,HelloWorld/server.py將輸出:

letian

而訪問http://127.0.0.1:5000/user/letian/,響應(yīng)為404 Not Found。

瀏覽器訪問http://127.0.0.1:5000/user/letian/friends,可以看到:

Hello letian. They are your friends.

HelloWorld/server.py輸出:

letian

8.3 轉(zhuǎn)換類型

由上面的示例可以看出,使用 Restful URL 得到的變量默認(rèn)為str對(duì)象。如果我們需要通過分頁顯示查詢結(jié)果,那么需要在url中有數(shù)字來指定頁數(shù)。按照上面方法,可以在獲取str類型頁數(shù)變量后,將其轉(zhuǎn)換為int類型。不過,還有更方便的方法,就是用flask內(nèi)置的轉(zhuǎn)換機(jī)制,即在route中指定該如何轉(zhuǎn)換。

新的服務(wù)器代碼:

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/page/')
def page(num):
    print(num)
    print(type(num))
    return 'hello world'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

`@app.route(‘/page/int:num‘)`會(huì)將num變量自動(dòng)轉(zhuǎn)換成int類型。

運(yùn)行上面的程序,在瀏覽器中訪問http://127.0.0.1:5000/page/1,HelloWorld/server.py將輸出如下內(nèi)容:

1

如果訪問的是http://127.0.0.1:5000/page/asd,我們會(huì)得到404響應(yīng)。

在官方資料中,說是有3個(gè)默認(rèn)的轉(zhuǎn)換器:

int     accepts integers

float     like int but for floating point values

path     like the default but also accepts slashes

看起來夠用了。

8.4 一個(gè)有趣的用法

如下編寫服務(wù)器代碼:

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/page/-')
def page(num1, num2):
    print(num1)
    print(num2)
    return 'hello world'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

在瀏覽器中訪問http://127.0.0.1:5000/page/11-22,HelloWorld/server.py會(huì)輸出:

11

22

8.5 編寫轉(zhuǎn)換器

自定義的轉(zhuǎn)換器是一個(gè)繼承werkzeug.routing.BaseConverter的類,修改to_pythonto_url方法即可。to_python方法用于將url中的變量轉(zhuǎn)換后供被`@app.route包裝的函數(shù)使用,to_url方法用于flask.url_for`中的參數(shù)轉(zhuǎn)換。

下面是一個(gè)示例,將HelloWorld/server.py修改如下:

from flask import Flask, url_for
 
from werkzeug.routing import BaseConverter
 
 
class MyIntConverter(BaseConverter):
 
    def __init__(self, url_map):
        super(MyIntConverter, self).__init__(url_map)
 
    def to_python(self, value):
        return int(value)
 
    def to_url(self, value):
        return value * 2
 
 
app = Flask(__name__)
app.url_map.converters['my_int'] = MyIntConverter
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/page/')
def page(num):
    print(num)
    print(url_for('page', num=123))   # page 對(duì)應(yīng)的是 page函數(shù) ,num 對(duì)應(yīng)對(duì)應(yīng)`/page/`中的num,必須是str
    return 'hello world'
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

瀏覽器訪問http://127.0.0.1:5000/page/123后,HelloWorld/server.py的輸出信息是:

123

/page/123123

九、使用url_for生成鏈接

工具函數(shù)url_for可以讓你以軟編碼的形式生成url,提供開發(fā)效率。

9.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

9.2 編寫代碼

編輯HelloWorld/server.py:

from flask import Flask, url_for
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    pass
 
@app.route('/user/')
def user(name):
    pass
 
@app.route('/page/')
def page(num):
    pass
 
@app.route('/test')
def test():
    print(url_for('hello_world'))
    print(url_for('user', name='letian'))
    print(url_for('page', num=1, q='hadoop mapreduce 10%3'))
    print(url_for('static', filename='uploads/01.jpg'))
    return 'Hello'
 
if __name__ == '__main__':
    app.run(debug=True)

運(yùn)行HelloWorld/server.py。然后在瀏覽器中訪問http://127.0.0.1:5000/test,HelloWorld/server.py將輸出以下信息:

/
/user/letian
/page/1?q=hadoop+mapreduce+10%253
/static/uploads/01.jpg

十、使用redirect重定向網(wǎng)址

redirect函數(shù)用于重定向,實(shí)現(xiàn)機(jī)制很簡(jiǎn)單,就是向客戶端(瀏覽器)發(fā)送一個(gè)重定向的HTTP報(bào)文,瀏覽器會(huì)去訪問報(bào)文中指定的url。

10.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

10.2 編寫代碼

使用redirect時(shí),給它一個(gè)字符串類型的參數(shù)就行了。

編輯HelloWorld/server.py:

from flask import Flask, url_for, redirect
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'hello world'
 
@app.route('/test1')
def test1():
    print('this is test1')
    return redirect(url_for('test2'))
 
@app.route('/test2')
def test2():
    print('this is test2')
    return 'this is test2'
 
if __name__ == '__main__':
    app.run(debug=True)

運(yùn)行HelloWorld/server.py,在瀏覽器中訪問http://127.0.0.1:5000/test1,瀏覽器的url會(huì)變成http://127.0.0.1:5000/test2,并顯示:

this is test2

十一、使用Jinja2模板引擎

模板引擎負(fù)責(zé)MVC中的V(view,視圖)這一部分。Flask默認(rèn)使用Jinja2模板引擎。

Flask與模板相關(guān)的函數(shù)有:

  • flask.render_template(template_name_or_list, **context) 
    Renders a template from the template folder with the given context.

  • flask.render_template_string(source, **context) 
    Renders a template from the given template source string with the given context.

  • flask.get_template_attribute(template_name, attribute) 
    Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code.

這其中常用的就是前兩個(gè)函數(shù)。

這個(gè)實(shí)例中使用了模板繼承、if判斷、for循環(huán)。

11.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

11.2 創(chuàng)建并編輯HelloWorld/templates/default.html

內(nèi)容如下:

<html>
<head>
    <title>
        {% if page_title %}
            {{ page_title }}
        {% endif %}
    </title>
</head>
 
<body>
    {% block body %}{% endblock %}
 
 
```
可以看到,在``標(biāo)簽中使用了if判斷,如果給模板傳遞了`page_title`變量,顯示之,否則,不顯示。
``標(biāo)簽中定義了一個(gè)名為`body`的block,用來被其他模板文件繼承。
### 11.3 創(chuàng)建并編輯HelloWorld/templates/user_info.html
內(nèi)容如下:
```
{% extends "default.html" %}
 
{% block body %}
    {% for key in user_info %}
 
        {{ key }}: {{ user_info[key] }} 
 
 
    {% endfor %}
{% endblock %}

變量user_info應(yīng)該是一個(gè)字典,for循環(huán)用來循環(huán)輸出鍵值對(duì)。

11.4 編輯HelloWorld/server.py

內(nèi)容如下:

from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user')
def user():
    user_info = {
        'name': 'letian',
        'email': '123@aa.com',
        'age':0,
        'github': 'https://github.com/letiantian'
    }
    return render_template('user_info.html', page_title='letian\'s info', user_info=user_info)
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

render_template()函數(shù)的第一個(gè)參數(shù)指定模板文件,后面的參數(shù)是要傳遞的數(shù)據(jù)。

11.5 運(yùn)行與測(cè)試

運(yùn)行HelloWorld/server.py:

$ python3 HelloWorld/server.py

在瀏覽器中訪問http://127.0.0.1:5000/user

查看網(wǎng)頁源碼:

<html>
<head>
    <title>
            letian&&9;s info
    </title>
</head>
<body>
        name: letian <br/>
        email: 123@aa.com <br/>
        age: 0 <br/>
        github: https://github.com/letiantian <br/>
</body>
</html>

十二、自定義404等錯(cuò)誤的響應(yīng)

要處理HTTP錯(cuò)誤,可以使用flask.abort函數(shù)。

12.1 示例1:簡(jiǎn)單入門

建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

代碼

編輯HelloWorld/server.py:

from flask import Flask, render_template_string, abort
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user')
def user():
    abort(401)  # Unauthorized 未授權(quán)
    print('Unauthorized, 請(qǐng)先登錄')
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

效果

運(yùn)行HelloWorld/server.py,瀏覽器訪問http://127.0.0.1:5000/user

要注意的是,HelloWorld/server.py中abort(401)后的print并沒有執(zhí)行。

12.2 示例2:自定義錯(cuò)誤頁面

代碼

將服務(wù)器代碼改為:

from flask import Flask, render_template_string, abort
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/user')
def user():
    abort(401)  # Unauthorized
 
 
@app.errorhandler(401)
def page_unauthorized(error):
    return render_template_string('
 Unauthorized 
{{ error_info }}', error_info=error), 401
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

page_unauthorized函數(shù)返回的是一個(gè)元組,401 代表HTTP 響應(yīng)狀態(tài)碼。如果省略401,則響應(yīng)狀態(tài)碼會(huì)變成默認(rèn)的 200。

效果

運(yùn)行HelloWorld/server.py,瀏覽器訪問http://127.0.0.1:5000/user

十三、用戶會(huì)話

session用來記錄用戶的登錄狀態(tài),一般基于cookie實(shí)現(xiàn)。

下面是一個(gè)簡(jiǎn)單的示例。

13.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

13.2 編輯HelloWorld/server.py

內(nèi)容如下:

from flask import Flask, render_template_string, \
    session, request, redirect, url_for
 
app = Flask(__name__)
 
app.secret_key = 'F12Zr47j\3yX R~X@H!jLwf/T'
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/login')
def login():
     return render_template_string(page)
@app.route('/do_login', methods=['POST'])
def do_login():
    name = request.form.get('user_name')
    session['user_name'] = name
    return 'success'
 
 
@app.route('/show')
def show():
    return session['user_name']
 
 
@app.route('/logout')
def logout():
    session.pop('user_name', None)
    return redirect(url_for('login'))
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

13.3 代碼的含義

app.secret_key用于給session加密。

/login中將向用戶展示一個(gè)表單,要求輸入一個(gè)名字,submit后將數(shù)據(jù)以post的方式傳遞給/do_login,/do_login將名字存放在session中。

如果用戶成功登錄,訪問/show時(shí)會(huì)顯示用戶的名字。此時(shí),打開firebug等調(diào)試工具,選擇session面板,會(huì)看到有一個(gè)cookie的名稱為session

/logout用于登出,通過將session中的user_name字段pop即可。Flask中的session基于字典類型實(shí)現(xiàn),調(diào)用pop方法時(shí)會(huì)返回pop的鍵對(duì)應(yīng)的值;如果要pop的鍵并不存在,那么返回值是pop()的第二個(gè)參數(shù)。

另外,使用redirect()重定向時(shí),一定要在前面加上return。

13.4 效果

進(jìn)入http://127.0.0.1:5000/login,輸入name,點(diǎn)擊submit

進(jìn)入http://127.0.0.1:5000/show查看session中存儲(chǔ)的name:

Python如何使用Web框架Flask開發(fā)項(xiàng)目

13.5 設(shè)置sessin的有效時(shí)間

下面這段代碼來自Is there an easy way to make sessions timeout in flask?:

from datetime import timedelta
from flask import session, app
 
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)

這段代碼將session的有效時(shí)間設(shè)置為5分鐘。

十四、使用Cookie

Cookie是存儲(chǔ)在客戶端的記錄訪問者狀態(tài)的數(shù)據(jù)。 常用的用于記錄用戶登錄狀態(tài)的session大多是基于cookie實(shí)現(xiàn)的。

cookie可以借助flask.Response來實(shí)現(xiàn)。下面是一個(gè)示例。

14.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

14.2 代碼

修改HelloWorld/server.py:

from flask import Flask, request, Response, make_response
import time
 
app = Flask(__name__)
 
 
@app.route('/')
def hello_world():
    return 'hello world'
 
 
@app.route('/add')
def login():
    res = Response('add cookies')
    res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
    return res
 
 
@app.route('/show')
def show():
    return request.cookies.__str__()
 
 
@app.route('/del')
def del_cookie():
    res = Response('delete cookies')
    res.set_cookie('name', '', expires=0)
    return res
 
 
if __name__ == '__main__':
    app.run(port=5000, debug=True)

由上可以看到,可以使用Response.set_cookie添加和刪除cookie。expires參數(shù)用來設(shè)置cookie有效時(shí)間,它的值可以是datetime對(duì)象或者unix時(shí)間戳,筆者使用的是unix時(shí)間戳。

res.set_cookie(key='name', value='letian', expires=time.time()+6*60)

上面的expire參數(shù)的值表示cookie在從現(xiàn)在開始的6分鐘內(nèi)都是有效的。

要?jiǎng)h除cookie,將expire參數(shù)的值設(shè)為0即可:

res.set_cookie('name', '', expires=0)

set_cookie()函數(shù)的原型如下:

set_cookie(key, value=&rsquo;&rsquo;, max_age=None, expires=None, path=&rsquo;/&lsquo;, domain=None, secure=None, httponly=False)

Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too. 
Parameters:

key &ndash; the key (name) of the cookie to be set. 
value &ndash; the value of the cookie. 
max_age &ndash; should be a number of seconds, or None (default) if the cookie should last only as long as the client&rsquo;s browser session.

expires &ndash; should be a datetime object or UNIX timestamp.

domain &ndash; if you want to set a cross-domain cookie. For example, domain=”.example.com” will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.

path &ndash; limits the cookie to a given path, per default it will span the whole domain.

14.3 運(yùn)行與測(cè)試

運(yùn)行HelloWorld/server.py:

$ python3 HelloWorld/server.py

使用瀏覽器打開http://127.0.0.1:5000/add,瀏覽器界面會(huì)顯示

add cookies

下面查看一下cookie,如果使用firefox瀏覽器,可以用firebug插件查看。打開firebug,選擇Cookies選項(xiàng),刷新頁面,可以看到名為name的cookie,其值為letian。

在“網(wǎng)絡(luò)”選項(xiàng)中,可以查看響應(yīng)頭中類似下面內(nèi)容的設(shè)置cookie的HTTP「指令」:

Set-Cookie: name=letian; Expires=Sun, 29-Jun-2014 05:16:27 GMT; Path=/

在cookie有效期間,使用瀏覽器訪問http://127.0.0.1:5000/show,可以看到:

{'name': 'letian'}

十五、閃存系統(tǒng) flashing system

Flask的閃存系統(tǒng)(flashing system)用于向用戶提供反饋信息,這些反饋信息一般是對(duì)用戶上一次操作的反饋。反饋信息是存儲(chǔ)在服務(wù)器端的,當(dāng)服務(wù)器向客戶端返回反饋信息后,這些反饋信息會(huì)被服務(wù)器端刪除。

下面是一個(gè)示例。

15.1 建立Flask項(xiàng)目

按照以下命令建立Flask項(xiàng)目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

15.2 編寫HelloWorld/server.py

內(nèi)容如下:

from flask import Flask, flash, get_flashed_messages
import time
 
app = Flask(__name__)
app.secret_key = 'some_secret'
 
 
@app.route('/')
def index():
    return 'hi'
 
 
@app.route('/gen')
def gen():
    info = 'access at '+ time.time().__str__()
    flash(info)
    return info
 
 
@app.route('/show1')
def show1():
    return get_flashed_messages().__str__()
 
 
@app.route('/show2')
def show2():
    return get_flashed_messages().__str__()
 
 
if __name__ == "__main__":
    app.run(port=5000, debug=True)

15.3 效果

運(yùn)行服務(wù)器:

$ python3 HelloWorld/server.py

打開瀏覽器,訪問http://127.0.0.1:5000/gen,瀏覽器界面顯示(注意,時(shí)間戳是動(dòng)態(tài)生成的,每次都會(huì)不一樣,除非并行訪問):

access at 1404020982.83

查看瀏覽器的cookie,可以看到session,其對(duì)應(yīng)的內(nèi)容是:

.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWCAEAJKBGq8.BpE6dg.F1VURZa7VqU9bvbC4XIBO9-3Y4Y

再一次訪問http://127.0.0.1:5000/gen,瀏覽器界面顯示:

access at 1404021130.32

cookie中session發(fā)生了變化,新的內(nèi)容是:

.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWLBaMg1yrfCtciz1rfIEGxRbCwAhGjC5.BpE7Cg.Cb_B_k2otqczhknGnpNjQ5u4dqw

然后使用瀏覽器訪問http://127.0.0.1:5000/show1,瀏覽器界面顯示:

['access at 1404020982.83', 'access at 1404021130.32']

這個(gè)列表中的內(nèi)容也就是上面的兩次訪問http://127.0.0.1:5000/gen得到的內(nèi)容。此時(shí),cookie中已經(jīng)沒有session了。

如果使用瀏覽器訪問http://127.0.0.1:5000/show1或者h(yuǎn)ttp://127.0.0.1:5000/show2,只會(huì)得到:

[]

15.4 高級(jí)用法

flash系統(tǒng)也支持對(duì)flash的內(nèi)容進(jìn)行分類。修改HelloWorld/server.py內(nèi)容:

from flask import Flask, flash, get_flashed_messages
import time
 
app = Flask(__name__)
app.secret_key = 'some_secret'
 
 
@app.route('/')
def index():
    return 'hi'
 
 
@app.route('/gen')
def gen():
    info = 'access at '+ time.time().__str__()
    flash('show1 '+info, category='show1')
    flash('show2 '+info, category='show2')
    return info
 
 
@app.route('/show1')
def show1():
    return get_flashed_messages(category_filter='show1').__str__()
 
@app.route('/show2')
def show2():
    return get_flashed_messages(category_filter='show2').__str__()
 
 
if __name__ == "__main__":
    app.run(port=5000, debug=True)

某一時(shí)刻,瀏覽器訪問http://127.0.0.1:5000/gen,瀏覽器界面顯示:

access at 1404022326.39

不過,由上面的代碼可以知道,此時(shí)生成了兩個(gè)flash信息,但分類(category)不同。

使用瀏覽器訪問http://127.0.0.1:5000/show1,得到如下內(nèi)容:

['1 access at 1404022326.39']

而繼續(xù)訪問http://127.0.0.1:5000/show2,得到的內(nèi)容為空:

[]

15.5 在模板文件中獲取flash的內(nèi)容

在Flask中,get_flashed_messages()默認(rèn)已經(jīng)集成到Jinja2模板引擎中,易用性很強(qiáng)。

到此,關(guān)于“Python如何使用Web框架Flask開發(fā)項(xiàng)目”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI