我尝试使用 falcon 编写 API REST。
on_get方法效果很好,但是使用on_post时,无法获取POST请求的正文,不知道为什么
class ProfileUpdate(object):
def on_post(self, req, resp):
data = json.load(req.stream)
print(data)
resp.body = {"test": "answer"}
resp.status = falcon.HTTP_200
return resp
def setup_profile():
app = falcon.API()
profile_update = ProfileUpdate()
app.add_route('/profiles', profile_update)
return app
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 135, in handle
self.handle_request(listener, req, client, addr)
File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/usr/local/lib/python3.7/site-packages/falcon/api.py", line 318, in __call__
body, length = self._get_body(resp, env.get('wsgi.file_wrapper'))
File "/usr/local/lib/python3.7/site-packages/falcon/api.py", line 820, in _get_body
body = body.encode('utf-8')
AttributeError: 'dict' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)
我正在使用 Postman 来测试 API。我尝试在 POSTMAN 中使用以下主体(原始 -> JSON)
{
"email":"test"
}
Run Code Online (Sandbox Code Playgroud)
我缺少什么?
您可以使用请求原始正文 JSON media,也可以附加media到响应。
\n\n\n如果您\xe2\x80\x99正在创建 JSON API,则需要零配置。只需访问或设置适当的媒体属性,然后让 Falcon 为您完成繁重的工作。
\n
class EchoResource:\n def on_post(self, req, resp):\n message = req.media.get("message")\n resp.media = {\n "message": message\n }\n resp.status = falcon.HTTP_200\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n警告:
\n\n一旦根据请求调用媒体,它将消耗请求流。
\n
| 归档时间: |
|
| 查看次数: |
2340 次 |
| 最近记录: |