Python猎鹰-获得邮政d

2024-06-06 16:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在我的项目中使用falcon包。问题是我没有找到从HTTP post请求获取正文数据的方法。

我使用了示例中的代码,但是req.stream.read()没有按预期返回JSON。

代码是:

raw_json = req.stream.read()
result.json(raw_json, encoding='utf-8')
resp.body = json.dumps(result_json, encoding='utf-8')

如何获取POST数据?

谢谢你的帮助


Tags: 数据项目方法代码jsonhttpreadstream
3条回答

对这个问题的深入研究导致了下面的linked issue on github。它指出,falcon框架至少在其0.3版和Python2中,如果数据被恰当地转义,则不会将其解析为字符串。我们可以使用更多的信息来了解您试图通过POST请求发送哪些数据以及发送的格式,比如它是以简单文本的形式发送的,或者使用头信息内容类型:application/json,或者它是通过HTML表单发送的。

虽然问题还不清楚,但我仍然建议尝试使用bounded_stream,而不是stream,如:

raw_json = req.bounded_stream.read()
result.json(raw_json, encoding='utf-8')
resp.body = json.dumps(result_json, encoding='utf-8')

对于官方文档,建议使用bounded_stream,如果内容长度未定义或为0等不确定条件,或者如果头信息完全丢失。

有界流在官方falcon documentation中描述如下。

File-like wrapper around stream to normalize certain differences between the native input objects employed by different WSGI servers. In particular, bounded_stream is aware of the expected Content-Length of the body, and will never block on out-of-bounds reads, assuming the client does not stall while transmitting the data to the server.

Falcon接收来自客户端的数据的WSGI包装器作为缓冲对象传递的HTTP请求数据,由于性能原因,它可能没有在数据上运行正确的解析以转换为更可用的数据结构。

您要查找的字段的名称有些混乱,但它是req.media

Returns a deserialized form of the request stream. When called, it will attempt to deserialize the request stream using the Content-Type header as well as the media-type handlers configured via falcon.RequestOptions.

如果请求是JSON,req.media已经包含python dict

非常感谢Ryan(和Prateek Jain)的回答。

解决方法很简单,就是放app.req_options.auto_parse_form_urlencoded=True。例如:

import falcon

class ThingsResource(object):
    def on_post(self, req, resp):
        value = req.get_param("value", required=True)
        #do something with value

app = falcon.API()
app.req_options.auto_parse_form_urlencoded=True

things = ThingsResource()

app.add_route('/things', things)

相关问题 更多 >