Future does not complete

Viewed 18

I am working on creating a asyncio.Future callback for requests whereby I store the body of the response in json format and return this result. I initially wanted to create a callback on the function on_response, however I was not certain how to implement this. Therefore, I decided to include option parameters to add into the callable such as url.

For example:

import asyncio
from functools import partial as func
import requests
import json

url = "https://www.scrapethissite.com/pages/ajax-javascript/?ajax=true&year=2015"

class schedulerLoop(asyncio.Future):
    def __init__(self, url):
        super(schedulerLoop, self).__init__()
        self._url = url
    
    @staticmethod
    def unwrapper(funct):
        return funct()

    def _future(self, *args):
        return self.add_done_callback(func(self.unwrapper, *args))

    async def on_response(self):
        if self.done():
            obj = await self._future(func(requests.get, self._url))
            body = json.loads(obj)
            return body
        else:
            self.exception()

async def main(loop):
    await loop.on_response()

loop = schedulerLoop(url)

if __name__ == '__main__':
    asyncio.run(main(loop))

I find that I get:

asyncio.exceptions.InvalidStateError: Exception is not set.

Which supposes that on_response the Future is not done, and so we get a False result but there seems be no no Exception neither.

0 Answers
Related