gpt4 book ai didi

python-3.x - Falcon 无法读取请求正文

转载 作者:行者123 更新时间:2023-12-04 00:41:19 28 4
gpt4 key购买 nike

我正在尝试使用 JSON 数据读取一个简单的请求正文。

请求正文:

[
{
...data
},
{
...data
}
]

当我尝试时(在 EventResource 中)
def on_post(self, req, resp):

print(req.stream.read())

以下登录到控制台: b''
我不知道我做错了什么,也不知道为什么它不显示我的 body 数据。我在执行此操作时看到的每个示例实际上都记录了数据而不是我得到的数据。

Requirements.txt(可能有些断章取意,但为了确定起见,我添加了完整列表。)
astroid==1.5.3
bson==0.5.0
cffi==1.11.2
click==6.7
falcon==1.4.1
falcon-auth==1.1.0
falcon-jsonify==0.1.1
Flask==0.12.2
greenlet==0.4.12
gunicorn==19.7.1
isort==4.2.15
itsdangerous==0.24
Jinja2==2.10
lazy-object-proxy==1.3.1
MarkupSafe==1.0
mccabe==0.6.1
mimeparse==0.1.3
mongoengine==0.15.0
pycparser==2.18
PyJWT==1.5.3
pylint==1.7.4
pymongo==3.5.1
python-mimeparse==1.6.0
pytz==2017.3
readline==6.2.4.1
six==1.11.0
Werkzeug==0.12.2
wrapt==1.10.11

应用程序
api = falcon.API(middleware=[
falcon_jsonify.Middleware(help_messages=settings.DEBUG)
])

路线.py
from app import api
from resources.event import EventResource
from resources.venue import VenueResource

# EventResources
api.add_route('/api/event', EventResource())
api.add_route('/api/event/{event_id}', EventResource())
api.add_route('/api/venue/{venue_id}/events', EventResource())

# VenueResources
api.add_route('/api/venue', VenueResource())
api.add_route('/api/venue/{venue_id}', VenueResource())
api.add_route('/api/event/{event_id}/venue', VenueResource())

我用 gunicorn routes:api --reload 运行我的项目

示例 POST 请求(记录 b'' ):
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:8000/api/event

我添加的唯一标题是 Content-Type/ application/json
我已通读 this但这对我没有帮助。

最佳答案

该行为的发生是因为您的

falcon_jsonify.Middleware(help_messages=settings.DEBUG)

流已经被它读取了。您需要使用 req.json在这种情况下。如果删除中间件,则 req.stream.read()将正确返回值。如果你看中间件的 process_request方法
def process_request(self, req, resp):
if not req.content_length:
return

body = req.stream.read()
req.json = {}
self.req = req
req.get_json = self.get_json

try:
req.json = json.loads(body.decode('utf-8'))

except ValueError:
self.bad_request("Malformed JSON", "Syntax error")

except UnicodeDecodeError:
self.bad_request("Invalid encoding", "Could not decode as UTF-8")

您可以看到中间件读取正文然后在 req.json 中吐出相同的内容作为解析对象。但是原始 body 不会保存在其他任何地方。一旦读取了请求流,您就清空了它的缓冲区并且不会再次获取数据。因此你得到 b''

关于python-3.x - Falcon 无法读取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663623/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com