0

I have the following method:

    async def make_request(self, url):
        async with aiohttp.ClientSession() as session:
            async with self.limit, session.get(url=url) as response:
                resp = await response.read()
                await asyncio.sleep(self.rate)
                return resp

How to check if resp contains json? so that I could format in json e.g. json.dumps(resp) perhaps? and if the resp type is html then i will have to traverse the html tree to extract the resp value

I have tried:

    async def make_request(self, url):
        async with aiohttp.ClientSession() as session:
            async with self.limit, session.get(url=url) as response:
                resp = await response.json()
                await asyncio.sleep(self.rate)
                return resp

But it errors out if the resp contains html

Shery
  • 1,808
  • 5
  • 27
  • 51

1 Answers1

1

As mentioned above checking the Content-Type header should be the first step; however if for any reason that header is missing or is incorrect you can always use:

text = await response.text()
try:
    data = json.loads(text)
except ValueError as exc:
    print("cannot parse JSON: %s" % exc)
    # use text value 

Ionut Ticus
  • 2,683
  • 2
  • 17
  • 25