json - Python 3.6 : get JSON from aiohttp request

标签 json request http-post python-3.6 aiohttp

我有一些使用 aiohttp 的应用程序。

我将 POST 请求发送到适当的端点,例如:

POST mysite.com/someendpoind/

数据类似于:

{"param1": "value1", "param2": "value2", ..., "paramn": None}

然后在后端,我想在此请求中添加一些额外的条件:

data = await request.json()
data["additional_conditional"] = True

但是 request.json() 失败并出现错误:

[ERROR] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/aiohttp/web_protocol.py", line 422, in start
resp = yield from self._request_handler(request)
File "/usr/local/lib/python3.5/dist-packages/aiohttp/web.py", line 306, in _handle
resp = yield from handler(request)
File "/usr/local/lib/python3.5/dist-packages/aiohttp_session/__init__.py", line 129, in middleware
response = yield from handler(request)
File "/opt/bikeamp/auth/__init__.py", line 57, in wrapped
return (yield from f(request, user))
File "<my_module>.py", line 185, in <my_func>
data_json = await request.json()
File "/usr/local/lib/python3.5/dist-packages/aiohttp/web_request.py", line 469, in json
return loads(body)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

然后我决定以某种方式检查我的请求的内容是什么:

await request.read()

b'field1=value1&field2=value2&field3=value3&field4=&field5=&field6='

所以,我不确定,但问题可能出在空参数上。

另外,我试图通过以下方式获取这些数据:

data = await request.post()
data["additional_condition"] = True

但这会返回MultiDictProxy。 Python 无法 pickle 这些对象。

有已知的解决方案吗?

最佳答案

我也遇到了同样的问题,如果帖子类似于 {"email": "some@email.com"} 检查它:

  @router('/', methods=['POST', ])
    async def post_request(request):    

        post = await request.post()
        email = post.get('email')   #  because it's MultiDict 
        logging.warning(post)       #  see post details
        logging.warning(email)      #  shows value "some@email.com" 

        json = await request.text() #
        logging.warning(json)       #  shows json if it was ajax post request

关于json - Python 3.6 : get JSON from aiohttp request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46180781/

相关文章:

java - 如何使用JAVA查询标点符号敏感术语的Marklogic?

json - 将 heredoc 声明压缩到 bash 中的一行?

request - 如何在 ServiceStack 中获取请求的时间戳?

post - Retrofit 2.0 无法将请求正文转换为 JSON

android - 带有 JSON 字符串的 HTTP post

Android HttpPost 请求不发布

android - 如何使用 Retrofit 发送数组/列表

json - 使用 ObjectMapper 的不同类型 JSON 文件

java - Struts 2 Action 中的 Android GCM 服务器

python - 如何获取美丽汤标签的内容?