异步网络请求,无法正确进行身份验证

async web request, unable to do authentication correctly

我一直在尝试编写一个 e621 采集器,虽然我想以异步方式进行,但我似乎无法让身份验证工作

当它 returns “响应”它时 returns 什么都没有,因为授权是错误的。我知道细节是正确的,但我不确定如何在异步编程中做到这一点。任何帮助表示赞赏!谢谢!

async def main():
    async with aiohttp.ClientSession() as session:

        url = 'https://e621.net/posts.json?limit=2&'

        params = {'user-agent':'frbottest/0.0.1 (by Vaston on e621)'}
        async with session.get(url, params=params, auth=aiohttp.BasicAuth(apiUser, apiKey)) as resp:
            resp = await resp.json(content_type=None)

            content = await resp.json()

            print(content['url'])


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

事实证明,e621 要求您将 headers 放入您的请求中才能正确授权。无需使用 authparams 组件,您只是在 session 的定义中缺少 header 字典。请参阅此处(只需将代理和密钥占位符替换为您的 apiUserapiKey 值):

import asyncio
import aiohttp
import json

headers = {
  'User-Agent': '<my_agent>',
  'Authorization': 'Basic <my_key>'
}

async def main():
  async with aiohttp.ClientSession(headers=headers) as session:
    url = 'https://e621.net/posts.json?limit=2&'

    async with session.get(url) as resp:
      resp = await resp.json(content_type=None)
      print(json.dumps(resp.get('posts')[0], indent=2))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())