【问题标题】:async web request, unable to do authentication correctly异步网络请求,无法正确进行身份验证
【发布时间】:2021-06-01 22:34:15
【问题描述】:

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

当它返回“resp”时,它什么也不返回,因为身份验证是错误的。我知道细节是正确的,但我不确定如何在异步编程中做到这一点。任何帮助表示赞赏!谢谢!

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

【问题讨论】:

    标签: python asynchronous python-asyncio aiohttp


    【解决方案1】:

    事实证明,e621 要求您将标头放入请求中以正确授权。无需使用authparams 组件,您只是在session 的定义中缺少标题字典。请参见此处(只需将代理和密钥占位符替换为您的 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())
    

    【讨论】:

    • 我真的很想给你解决方案(因为它确实解决了我的问题),但你能解释一下为什么会这样吗?
    • @Hunter e621 中授权的工作方式是您在任何标识您的应用程序的 REST API 请求中发送标头。你可以阅读它here!
    • 啊谢谢!我对 API 的东西有点陌生,所以任何事情都会有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2014-09-09
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多