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

问题描述 投票:3回答:2

我试图通过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())

但是,我收到一个错误:

回溯(最近一次调用最后一次):文件“get_gem.py”,第34行,在loop.run_until_complete(get_gemini())文件“/home/thorad/anaconda3/lib/python3.6/asyncio/base_events.py”,行466,在run_until_complete中返回future.result()文件“get_gem.py”,第29行,在get_gemini async中使用aiohttp.request(method =“POST”,url = base_url + payload [“request”],headers = headers)as响应:文件“/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/client.py”,第692行,在aenter self._resp =从self._coro收到文件“/ home / thorad / anaconda3 /lib/python3.6/site-packages/aiohttp/client.py“,第277行,在_request resp = req.send(conn)文件”/home/thorad/anaconda3/lib/python3.6/site-packages/ aiohttp / client_reqrep.py“,第463行,发送writer.write_headers(status_line,self.headers)文件”/home/thorad/anaconda3/lib/python3.6/site-packages/aiohttp/http_writer.py“,第247行,在write_headers中[k + SEP + v + END表示k,v表示headers.items()])文件“/home/thorad/anaconda3/lib/python3.6/site-packages/aiohtt p / http_writer.py“,第247行,[k + SEP + v + END表示k,v表示headers.items()])TypeError:必须是str,而不是字节

这表明我不能将字节作为标题发送。

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

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

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

python http asynchronous python-asyncio aiohttp
2个回答
3
投票

这里的问题是b64encode返回字节,但这些可以很容易地转换为正确的unicode字符串。它对您的服务器没有任何影响。

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

0
投票

转换ascii中的有效负载:

payload = {
#ommited for brevity
}

encoded_payload = str.encode(json.dumps(payload))
b64 = base64.b64encode(encoded_payload)
b64 = b4.decode('ascii')  # conversion back to unicode

# 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())
© www.soinside.com 2019 - 2024. All rights reserved.