赞
踩
有几个地方涉及到headers:
使用requests包
import requests as req
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
# 按特定的头部发送
ret = requests.post(url, data=json.dumps(payload), headers=headers)
视图函数收到请求后,可以通过flask的request对象获取headers并作出判断
from flask import request
if (request.accept_mimetypes.accept_json) and (not request.accept_mimetypes.accept_html):
...
通常情况下,使用make_response
构造返回体,类似
# 2. 使用make_response 来构造响应信息
resp = make_response("index page2") # 响应体数据
resp.status = "999 itcast" # 状态码
resp.headers["City"] = "ShangHai" # 通过字典的形式添加响应头
return resp
一般我使用jsonify
直接返回字符串,这个方法本身已经构造了响应头,直接改一下就可以了,用以下函数替代原来的jsonify
就可以了,在设置头部的字典中传入参数就可以了。
# 构造可设置headers的返回,必须在上下文中使用
def jsonify_with_headers(some_data, setting_headers_dict):
some_data1 = jsonify(some_data)
for k in setting_headers_dict.keys():
some_data1.headers[k] = setting_headers_dict[k]
return some_data1
通过request调取可以看到返回头部的结果
In [36]: resp.headers
Out[36]: {'Content-Type': 'application/json;charset=utf-8', 'Content-Length': '71', 'Server': 'Werkzeug/0.14.1 Python/3.6.5', 'Date': 'Mon, 17 May 2021 03:04:23 GMT'}
通常我习惯直接发送json字符串,这种方式我觉得是最方便的
# data是某个字典
resp = req.post( 'http://host:port/api/', json=data)
print(resp.text)
...
input_dict = request.get_json()
...
其他的传参方式整体上逻辑差不多,但是在小的参数设置方便比较烦,要调试
用request发送表单
data = {'data':'''abcdefg\n'''}
resp = req.post( 'http://localhost:5555/api/', data=data)
print(resp.text)
发送的时候不用对字典做特别的处理,直接发送
后端这样接收是可以的
data = request.form.get('data')
但是如果这样接收就会乱码
data = request.get_data('data').decode('utf-8')
---
data=%E5%8C%97%E4%BA%AC%E5%B8%82%E9%AB%98
但是在postman中我用表单去发送这样又是可以解析的。所以应该是参数设置有点问题。
我看了下,如果要和postman一致,应该这么写
tem_str = '''一些文本内容'''
tem_str = tem_str.encode('utf-8')
# headers不加也可以
resp = req.post( 'http://localhost:5555/api/', data=tem_str,headers={'Content-Type':'multipart/form-data'})
print(resp.text)
暂时先这样,以前这方面还写过一篇类似的文章
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。