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.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']

上传文件


这一部分的代码参考自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
  • 11
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
提供的源码资源涵盖了小程序应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
您可以使用C#中的HttpClient类来创建一个HTTP客户端,并使用Post方法发送请求。下面是一个简单的示例代码: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main() { // 创建HttpClient实例 using (HttpClient client = new HttpClient()) { try { // 设置请求的URL string url = "https://example.com/api/endpoint"; // 准备要发送的数据(可以是一个JSON字符串、表单数据等) string data = "key1=value1&key2=value2"; // 声明HttpContent对象,用于包装要发送的数据 HttpContent content = new StringContent(data); // 设置Content-Type头部,根据实际情况进行设置 content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded"); // 发送POST请求,并获取响应 HttpResponseMessage response = await client.PostAsync(url, content); // 检查响应是否成功 if (response.IsSuccessStatusCode) { // 读取响应内容 string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("响应内容:\n" + responseContent); } else { Console.WriteLine("请求失败,状态码:" + response.StatusCode); } } catch (Exception ex) { Console.WriteLine("发生异常:" + ex.Message); } } } } ``` 在这个示例中,我们使用了HttpClient类来发送POST请求。首先,我们设置了请求的URL和要发送的数据。然后,我们创建了一个StringContent对象来包装数据,并设置了Content-Type头部。接下来,我们使用HttpClient的PostAsync方法发送请求,并获取响应。最后,我们检查响应的状态码,如果成功,我们读取响应内容并进行处理。 请注意,这只是一个简单的示例,实际情况可能会根据您的需求而有所不同。您可能需要根据实际情况设置其他的请求头部、处理异常等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值