我在发送闭源应用程序时遇到问题页眉中的内容类型不正确。
我接收的数据为"内容类型:application/x-www-form-urlencoded">
我应该将其作为"内容类型:应用程序/json"接收
下面是烧瓶服务器代码,使用 Flask 和 Flask-restful
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource, request
TEST_PROXY = "0.0.0.0"
TEST_PROXY_PORT = 1885
DEBUG = True
app = Flask(__name__)
api = Api(app)
class TEST(Resource):
def get(self, queue, subqueue):
parser = reqparse.RequestParser()
parser.add_argument('m', type=str, help='A message')
args = parser.parse_args()
TEST_queue = f'/{queue}/{subqueue}'
message = args.get('m')
return {'type': 'GET',
'message': args.get('m'),
'queue': TEST_queue}
def post(self, queue, subqueue):
TEST_queue = f'/{queue}/{subqueue}'
# here is the problem
# because of the incorrect header
# the returned data is empty.
message = request.data
return {'type': 'POST',
'message-length': len(message),
'queue': TEST_queue}
api.add_resource(TEST, '/TEST/<string:queue>/<string:subqueue>')
if __name__ == '__main__':
app.run(debug=DEBUG, host=TEST_PROXY, port=TEST_PROXY_PORT)
发送
POST http://localhost:1885/TEST/sub/sub2
Content-Type: application/json
{"status": {"current_time": "now"}}
请求数据填充了内容。
POST http://localhost:1885/TEST/sub/sub2
Content-Type: application/x-www-form-urlencoded
{"status": {"current_time": "now"}}
有效,但 requests.data 现在是空的,相反,数据已被解析,不再以不变的形式提供。
由于发送方是闭源的,因此无法在短时间内修复该端的问题。
有没有办法覆盖 POST 请求/此请求的错误内容类型,以便我可以访问原始发布的数据?
request.get_data()
而不是request.data
。
从文档中:
data
将传入的请求数据作为字符串包含,以防它附带 Werkzeug 无法处理的 mimetype。
和
get_data(cache=True, as_text=False, parse_form_data=False)
这会将来自客户端的缓冲传入数据读取到一个字节串中。默认情况下,这是缓存的,但可以通过将缓存设置为 False 来更改该行为。通常,在不先检查内容长度的情况下调用此方法是一个坏主意,因为客户端可能会发送数十兆字节或更多,从而导致服务器上出现内存问题。
但是最好检查request.content_type
中的值并从request.json
和request.form
中获取数据。