1. 程式人生 > >淺入淺出Flask框架:處理客戶端通過POST方法傳送的資料

淺入淺出Flask框架:處理客戶端通過POST方法傳送的資料

作為一種HTTP請求方法,POST用於向指定的資源提交要被處理的資料。我們在某網站註冊使用者、寫文章等時候,需要將資料儲存在伺服器中,這是一般使用POST方法。

本文使用python的requests庫模擬客戶端。

建立Flask專案

按照以下命令建立Flask專案HelloWorld:

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

簡單的POST

以使用者註冊為例子,我們需要向伺服器/register傳送使用者名稱name和密碼password

。如下編寫HelloWorld/index.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.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(debug=True)

@app.route('/register', methods=['POST'])是指url/register只接受POST方法。也可以根據需要修改methods引數,例如

@app.route('/register', methods=['GET'
, 'POST']) # 接受GET和POST方法

客戶端client.py內容如下:

import requests

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

print r.text

執行HelloWorld/index.py,然後執行client.pyclient.py將輸出:

welcome

HelloWorld/index.py在終端中輸出以下除錯資訊(通過print輸出):

Content-Length: 24
User-Agent: python-requests/2.2.1 CPython/2.7.6 Windows/8
Host: 127.0.0.1:5000
Accept: */*
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate, compress


ImmutableMultiDict([('password', u'123'), ('name', u'letian')])
letian
letian
[u'letian']
little apple

前6行是client.py生成的HTTP請求頭,由於print request.headers輸出。

print request.form的結果是:

ImmutableMultiDict([('password', u'123'), ('name', u'letian')])

這是一個ImmutableMultiDict物件。關於request.form,更多內容請參考flask.Request.form。關於ImmutableMultiDict,更多內容請參考werkzeug.datastructures.MultiDict

request.form['name']request.form.get('name')都可以獲取name對應的值。對於request.form.get()可以為引數default指定值以作為預設值。所以:

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

輸出的是預設值

little apple

如果name有多個值,可以使用request.form.getlist('name'),該方法將返回一個列表。我們將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

此時執行client.pyprint request.form.getlist('name')將輸出:

[u'letian', u'letian2']

上傳檔案

假設將上傳的圖片只允許’png’、’jpg’、’jpeg’、’git’這四種格式,通過url/upload使用POST上傳,上傳的圖片存放在伺服器端的static/uploads目錄下。

首先在專案HelloWorld中建立目錄static/uploads

$ mkdir HelloWorld/static/uploads

werkzeug庫可以判斷檔名是否安全,例如防止檔名是../../../a.png,安裝這個庫:

$ pip install werkzeug

修改HelloWorld/index.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'] = set(['png', 'jpg', 'jpeg', 'gif'])

# For a given file, return whether it's an allowed type or not
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['image01']
    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
        return 'hello, '+request.form.get('name', 'little apple')+'. success'
    else:
        return 'hello, '+request.form.get('name', 'little apple')+'. failed'

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

app.config中的config是字典的子類,可以用來設定自有的配置資訊,也可以設定自己的配置資訊。函式allowed_file(filename)用來判斷filename是否有後綴以及字尾是否在app.config['ALLOWED_EXTENSIONS']中。

客戶端上傳的圖片必須以image01標識。upload_file是上傳檔案對應的物件。app.root_path獲取index.py所在目錄在檔案系統中的絕對路徑。upload_file.save(path)用來將upload_file儲存在伺服器的檔案系統中,引數最好是絕對路徑,否則會報錯(網上很多程式碼都是使用相對路徑,但是筆者在使用相對路徑時總是報錯,說找不到路徑)。函式os.path.join()用來將使用合適的路徑分隔符將路徑組合起來。

好了,定製客戶端client.py

import requests

files = {'image01': open('01.jpg', 'rb')}
user_info = {'name': 'letian'}
r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=files)

print r.text

當前目錄下的01.jpg將上傳到伺服器。執行client.py,結果如下:

hello, letian. success

然後,我們可以在static/uploads中看到檔案01.jpg

要控制上產檔案的大小,可以設定請求實體的大小,例如:

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

不過,在處理上傳檔案時候,需要使用try:...except:...

如果要獲取上傳檔案的內容可以:

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

處理JSON

處理JSON時,要把請求頭和響應頭的Content-Type設定為application/json

修改HelloWorld/index.py

from flask import Flask, request, Response
import json

app = Flask(__name__)

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

@app.route('/json', methods=['POST'])
def my_json():
    print request.headers
    print request.json
    rt = {'info':'hello '+request.json['name']}
    return Response(json.dumps(rt),  mimetype='application/json')

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

修改後執行。

修改client.py

import requests, json

user_info = {'name': 'letian'}
headers = {'content-type': 'application/json'}
r = requests.post("http://127.0.0.1:5000/json", data=json.dumps(user_info), headers=headers)
print r.headers
print r.json()

執行client.py,將顯示:

CaseInsensitiveDict({'date': 'Tue, 24 Jun 2014 12:10:51 GMT', 'content-length': '24', 'content-type': 'application/json', 'server': 'Werkzeug/0.9.6 Python/2.7.6'})
{u'info': u'hello letian'}

HelloWorld/index.py的除錯資訊為:

Content-Length: 18
User-Agent: python-requests/2.2.1 CPython/2.7.6 Windows/8
Host: 127.0.0.1:5000
Accept: */*
Content-Type: application/json
Accept-Encoding: gzip, deflate, compress


{u'name': u'letian'}

這個比較簡單,就不多說了。另外,如果需要響應頭具有更好的可定製性,可以如下修改my_json()函式:

@app.route('/json', methods=['POST'])
def my_json():
    print request.headers
    print request.json
    rt = {'info':'hello '+request.json['name']}
    response = Response(json.dumps(rt),  mimetype='application/json')
    response.headers.add('Server', 'python flask')
    return response