python - Aiohttp:如何发送 header 中的字节?

标签 python http asynchronous python-asyncio aiohttp

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

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

这表明我无法将字节作为 header 发送。

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

  • 我尝试删除 'Content-Type': 'text/plain'

如何通过 aiohttp 发送字节作为 header ? 感谢您的帮助。

最佳答案

这里的问题是 b64encode 返回字节,但这些字节可以轻松转换为正确的 unicode 字符串。它不会对您的服务器产生影响。

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

关于python - Aiohttp:如何发送 header 中的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47974846/

相关文章:

python - 确定字符串是否为等值图

c# - Azure 分析服务的 RESTful API 不起作用

javascript - 是否可以在加载 jQuery 之前预先注册处理程序?

java - Android 上的异步套接字实现

python - 获取 gae 数据存储表中的记录总数

python - Python set 比 list 更节省空间吗?

python - 有没有一种快速方法来替换仅包含 1 和 -1 的 np.array 元素

html - 启用浏览器缓存静态资源

java - 无法缓存由 Spring MVC 提供的图像

c# - 异步 SHA256 哈希