Python Flask之处理客户端通过POST方法传送的数据(json文本,文件)

2024-03-16 15:58

本文主要是介绍Python Flask之处理客户端通过POST方法传送的数据(json文本,文件),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

作为一种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, requestapp = Flask(__name__)@app.route('/')
def hello_world():return 'hello world'@app.route('/register', methods=['POST'])
def register():print request.headersprint request.formprint 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内容如下(基于requests库编写的client,也可以使用urllib/urllib2实现):

import requestsuser_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 requestsuser_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 osapp = 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 requestsfiles = {'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 jsonapp = Flask(__name__)@app.route('/')
def hello_world():  return 'hello world'@app.route('/json', methods=['POST'])
def my_json():  print request.headersprint request.jsonrt = {'info':'hello '+request.json['name']}return Response(json.dumps(rt),  mimetype='application/json')if __name__ == '__main__':  app.run(debug=True)

修改后运行。

修改client.py:

import requests, jsonuser_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.headersprint request.jsonrt = {'info':'hello '+request.json['name']}response = Response(json.dumps(rt),  mimetype='application/json')response.headers.add('Server', 'python flask')return response

参考文献:
http://blog.csdn.net/yelena_11/article/details/53404892
http://www.pythondoc.com/flask/
http://python.jobbole.com/84003/

这篇关于Python Flask之处理客户端通过POST方法传送的数据(json文本,文件)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/815974

相关文章

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下