async web request, unable to do authentication correctly

Viewed 484

I've been trying to program a e621 grabber, although I wanted to do it in async, and this I can't seem to get the authentication to work

When it returns "resp" it returns nothing because the auth is wrong. I know the details are correct, but I'm unsure how to do this in async programming. Any help is appreciated! Thank you!

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

Turns out, e621 requires you to put headers into your request to authorize correctly. No need to use the auth or params components, you're just missing a header dictionary in your definition of session. See here (just replace the agent and key placeholders with your apiUser and apiKey values):

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