Python 3.6:从 aiohttp 请求中获取 JSON

sma*_*art 7 json http-post request aiohttp python-3.6

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

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

POST mysite.com/someendpoind/
Run Code Online (Sandbox Code Playgroud)

数据类似于:

{"param1": "value1", "param2": "value2", ..., "paramn": None}
Run Code Online (Sandbox Code Playgroud)

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

data = await request.json()
data["additional_conditional"] = True
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

await request.read()

b'field1=value1&field2=value2&field3=value3&field4=&field5=&field6='
Run Code Online (Sandbox Code Playgroud)

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

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

data = await request.post()
data["additional_condition"] = True
Run Code Online (Sandbox Code Playgroud)

但这又回来了MultiDictProxy。Python 不能腌制这些对象。

有没有已知的解决方案?

Vas*_*cal 4

我遇到了同样的问题,如果帖子类似于{"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
Run Code Online (Sandbox Code Playgroud)