首页 文章

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

提问于
浏览
3

我试图通过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 for k,v in headers.items()])文件“/home/thorad/anaconda3/lib/python3.6/site-packages/aioh ttp / http_writer.py“,第247行,[k SEP v END for k,v in headers.items()])TypeError:必须是str,而不是字节

这表明我不能将字节作为 Headers 发送 .

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

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

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

2 回答

  • 0

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

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

    转换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())
    

相关问题