淺入淺出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方法
具體請參考http-methods。
客戶端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.py
。client.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.py
,print request.form.getlist('name')
將輸出:
[u'letian', u'letian2']
上傳文件
這一部分的代碼參考自How to upload a file to the server in Flask。
假設將上傳的圖片只允許’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
來自:http://www.letiantian.me/2014-06-24-flask-process-post-data/