代码之家  ›  专栏  ›  技术社区  ›  tryzombie501

在不保存文件的情况下获取文件会导致不一致。py公司

  •  -1
  • tryzombie501  · 技术社区  · 6 年前

    因此,我有一个命令,它将用户在命令后说的任何话发送到网站api,并发送网站生成的文件。然而,我正在改用aiohttp,因为它不像标准请求函数那样阻塞

    这就是我处理正常请求的方式,它工作得很好:

          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似乎不那么容易理解。

    1 回复  |  直到 6 年前
        1
  •  2
  •   tryzombie501    6 年前

    戴先生从不和中走出来。py discord server发送了一个获取和发送数据的完美示例

    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")