0

I am creating a module that communicate with an API and I am thinking to create my function with asyncio. Right now my code look like this :

def getMethod(self, stuff:str=None): #yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    res = requests.get(endpoint, params=params, headers=header)
    return res

As you can see, I am using the request module to send the data. I think that I would need to do that :

import asyncio
async def getMethod(self, stuff:str=None): #yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    res = requests.get(endpoint, params=params, headers=header)
    yield res

Would that work to make my function async ? or should I also use something like httpx (or aiohttp) to be able to await for the result ? Like the following

async def getMethod(self, stuff:str=None): #yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    await res = httpx.get(endpoint, params=params, headers=header)
    return res

Thanks for your help. Trying to learn async python there.

Pitchkrak
  • 340
  • 1
  • 3
  • 11
  • 1
    You need a library that has async support, like in your last example. Make sure to use a client in `httpx` https://www.python-httpx.org/advanced/#why-use-a-client. Even inside a `async def` the call to `resquests.get` is still blocking. – Kassym Dorsel Jun 11 '20 at 12:59
  • Thanks. That is answering my question and what I thought. – Pitchkrak Jun 11 '20 at 13:04

1 Answers1

0

Recommand use httpx,async code like this:

async def getMethod(self, stuff: str = None):  # yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    async with httpx.AsyncClient(headers=header, params=params) as client:
        res = await client.get(endpoint, params=params, headers=header)
    return res
Cherrymelon
  • 412
  • 2
  • 7
  • 17