所以我有一个命令,它将用户在命令后所说的内容发送到网站api并发送网站生成的文件。但是我正在转换到aiohttp,因为它不会像standered requests函数一样阻塞
这就是我使用正常请求的方式,它工作正常:
elif (data[0].lower() == ">signgirl"):
await bot.send_typing(message.channel)
tmp = message.content.replace(">signgirl", "")
m = hashlib.md5()
m.update(tmp.encode('utf-8'))
print(tmp, m.hexdigest())
r = requests.post("http://localhost/sign.php", stream=True, data={'text': tmp})
if (r.status_code() == 200):
await bot.send_file(destination=message.channel, filename=str(m.hexdigest()+".png"), fp=r.raw)
然而,当我尝试使用aiohttp时,我不知道如何实际获取原始文件数据.. 所以我做了这个功能来实现它。但它不会让我返回图像,我不能检查http状态代码而不会导致错误。
async def post_data2(url, payload):
async with aiohttp.ClientSession() as session2:
async with session2.post(url, data=payload) as response2:
output = {}
output['data'] = await Image.open(BytesIO(response2.read()))
output['status'] = 200 #await str(response2.status()) #Why is this object not callable?
return output
我怎么能这样做?这可能吗? aiohttp似乎不那么容易理解。
答案 0 :(得分:1)
Mister Day" V"自己从discord.py discord服务器发送了一个获取和发送数据的完美示例
async with aiohttp.ClientSession() as session:
# or use a session you already have
async with session.get("http://example.com") as resp:
buffer = io.BytesIO(await resp.read())
# buffer is a file-like
await client.send_file(channel, fp=buffer, filename="whatever")