其他分享
首页 > 其他分享> > Aiohttp:如何在标头中发送字节?

Aiohttp:如何在标头中发送字节?

作者:互联网

我正在尝试通过aiohttp发送字节作为标头值:

payload = {
#ommited for brevity
}

encoded_payload = str.encode(json.dumps(payload))
b64 = base64.b64encode(encoded_payload)

# sign the requests
signature = hmac.new(str.encode(keys['private']), b64, hashlib.sha384).hexdigest()

headers = {
        'Content-Type': 'text/plain',
        'APIKEY': keys['public'],
        'PAYLOAD': b64, // base64 value
        'SIGNATURE': signature
    }

async with aiohttp.request(method="POST", url="example.com", headers=headers) as response:
    print(await response.text())

但是,我收到一个错误:

Traceback (most recent call last):
File “get_gem.py”, line 34, in
loop.run_until_complete(get_gemini())
File “/home/thorad/anaconda3/lib/python3.6/asyncio/base_events.py”, line 466, in run_until_complete
return future.result()
File “get_gem.py”, line 29, in get_gemini
async with aiohttp.request(method=”POST”, url=base_url + payload[“request”], headers=headers) as response:
File “/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/client.py”, line 692, in aenter
self._resp = yield from self._coro
File “/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/client.py”, line 277, in _request
resp = req.send(conn)
File “/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/client_reqrep.py”, line 463, in send
writer.write_headers(status_line, self.headers)
File “/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/http_writer.py”, line 247, in write_headers
[k + SEP + v + END for k, v in headers.items()])
File “/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/http_writer.py”, line 247, in
[k + SEP + v + END for k, v in headers.items()])
TypeError: must be str, not bytes

这表明我不能发送字节作为标头.

不幸的是,我正在使用的服务要求我这样做,否则它将返回错误.

>我尝试删除“ Content-Type”:“ text / plain”

如何通过aiohttp发送字节作为标头?
谢谢你的帮助.

解决方法:

这里的问题是b64encode返回字节,但是这些字节可以轻松转换为正确的unicode字符串.它与您的服务器无关.

>>> b64 = base64.b64encode(b'...')
>>> type(b64)
<class 'bytes'>
>>> b64 = base64.b64encode(b'...').decode('utf8')
>>> type(b64)
<class 'str'>

标签:asynchronous,http,python-asyncio,aiohttp,python
来源: https://codeday.me/bug/20191110/2014054.html