Search code examples
pythontornado

When using Python/Tornado, is it possible to call another API thru http request within a handler?


I have written a set of python REST APIs that are served by the Tornado web framework. The issue I am facing is like this: When handling endpoint1 or API1, I need to get at some data that endpoint2 or API2 can provide. So, inside the handler for endpoint1, I call something like this:

   class endpoint1(tornado.web.RequestHandler):
    .........   

      def get(self):
      ..........
         http_client = AsyncHTTPClient()
         url = "http://127.0.0.1:8686/v1/endpoint2"
         response = yield http_client.fetch(url)

But, the code just hangs at this point. My guess is it doesn't work since the framework is currently in the middle of servicing endpoint1 and I am trying to sneak in another request within. I am looking for suggestions on how to get this to work without using MQ or databases. I tried using nest_asyncio also - no dice. Any help appreciated


Solution

  • Turns out that nest_asyncio actually does the trick. Here is a link to another thread that explains it well: RuntimeError: This event loop is already running in python

    import nest_asyncio
    nest_asyncio.apply()
    
     class endpoint1(tornado.web.RequestHandler):
    .........   
    
      def get(self):
      ..........
         http_client = AsyncHTTPClient()
         url = "http://127.0.0.1:8686/v1/endpoint2"
         response = await http_client.fetch(url)