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使用GZIP压缩反回数据问题

《SpringBoot使用GZIP压缩反回数据问题》:本文主要介绍SpringBoot使用GZIP压缩反回数据问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录SpringBoot使用GZIP压缩反回数据1、初识gzip2、gzip是什么,可以干什么?3、Spr

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

Python实现特殊字符判断并去掉非字母和数字的特殊字符

《Python实现特殊字符判断并去掉非字母和数字的特殊字符》在Python中,可以通过多种方法来判断字符串中是否包含非字母、数字的特殊字符,并将这些特殊字符去掉,本文为大家整理了一些常用的,希望对大家... 目录1. 使用正则表达式判断字符串中是否包含特殊字符去掉字符串中的特殊字符2. 使用 str.isa

Spring 基于XML配置 bean管理 Bean-IOC的方法

《Spring基于XML配置bean管理Bean-IOC的方法》:本文主要介绍Spring基于XML配置bean管理Bean-IOC的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录一. spring学习的核心内容二. 基于 XML 配置 bean1. 通过类型来获取 bean2. 通过

python中各种常见文件的读写操作与类型转换详细指南

《python中各种常见文件的读写操作与类型转换详细指南》这篇文章主要为大家详细介绍了python中各种常见文件(txt,xls,csv,sql,二进制文件)的读写操作与类型转换,感兴趣的小伙伴可以跟... 目录1.文件txt读写标准用法1.1写入文件1.2读取文件2. 二进制文件读取3. 大文件读取3.1

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

Python处理函数调用超时的四种方法

《Python处理函数调用超时的四种方法》在实际开发过程中,我们可能会遇到一些场景,需要对函数的执行时间进行限制,例如,当一个函数执行时间过长时,可能会导致程序卡顿、资源占用过高,因此,在某些情况下,... 目录前言func-timeout1. 安装 func-timeout2. 基本用法自定义进程subp

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

Python结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验