Flask之处理客户端通过POST方法传送的数据
2016-11-30 10:16
441 查看
作为一种HTTP请求方法,POST用于向指定的资源提交要被处理的数据。我们在某网站注册用户、写文章等时候,需要将数据保存在服务器中,这是一般使用POST方法。
本文使用Python的requests库模拟客户端。
按照以下命令建立Flask项目HelloWorld:
以用户注册为例子,我们需要向服务器
具体请参考http-methods。
客户端
运行
而
前6行是client.py生成的HTTP请求头,由于
这是一个
输出的是默认值
如果
此时运行
这一部分的代码参考自How
to upload a file to the server in Flask。
假设将上传的图片只允许'png'、'jpg'、'jpeg'、'Git'这四种格式,通过url
首先在项目
修改
客户端上传的图片必须以
好了,定制客户端
当前目录下的
然后,我们可以在
要控制上产文件的大小,可以设置请求实体的大小,例如:
不过,在处理上传文件时候,需要使用
如果要获取上传文件的内容可以:
处理JSON时,要把请求头和响应头的
修改
修改后运行。
修改
运行
而
这个比较简单,就不多说了。另外,如果需要响应头具有更好的可定制性,可以如下修改
本文使用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在终端中输出以下调试信息(通过
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']
上传文件
这一部分的代码参考自Howto 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
相关文章推荐
- Python Flask之处理客户端通过POST方法传送的数据(json文本,文件)
- 浅入浅出Flask框架:处理客户端通过POST方法传送的数据
- Flask-处理客户端通过POST方法传送的数据
- 获取客户端ip地址方法和通过curl在命令行提交post数据到服务器
- 通过Curl、socket、file_get_contents三种方法使用POST提交数据
- 通过传参返回处理后数据的方法
- android 通过post发送数据 完成客户端登陆模块
- 补充 宝玉 之《URL欺骗之以假乱真!》之 POST 方法提交数据 之 处理!
- 补充 宝玉 之《URL欺骗之以假乱真!》之 POST 方法提交数据 之 处理!
- AJAX处理 POST数据中有特殊符号导致数据丢失的解决方法
- android 通过post发送数据完成客户端的登陆模块
- php处理json请求(php获取post请求的json数据的实现方法)
- 写通过POST方法向HTTP接口传递数据的程序
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- Android通过POST方法传递数据给服务器
- jquery ajax post 方法传送object 的list 数据给后台
- Android客户端通过GET和POST向服务器发送数据
- 两种HTTP方法服务器传送表单数据:GET和POST的区别
- http接口加密《一》:移动应用中,通过在客户端对访问的url进行加密处理来保护服务器上的数据
- jQuery get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据。