Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save BibMartin/ac4a80b6559d205e56eb8c06ba61df93 to your computer and use it in GitHub Desktop.

Select an option

Save BibMartin/ac4a80b6559d205e56eb8c06ba61df93 to your computer and use it in GitHub Desktop.
Asynchronous service with tornado
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
import time
import pandas as pd
from tornado import ioloop, web, httpserver, httpclient
class LongQueryHandler(web.RequestHandler):
def get(self):
response = [pd.Timestamp.utcnow().time().isoformat()] # Catch the current time.
time.sleep(0.1) # Wait 0.1 second.
response.append(pd.Timestamp.utcnow().time().isoformat()) # Catch the time again.
self.write(pd.json.dumps(response)) # Returns a JSON.
class SynchronousHandler(web.RequestHandler):
def get(self):
client = httpclient.HTTPClient()
output = [pd.Timestamp.utcnow().time().isoformat()]
response = client.fetch('http://localhost:8888/longquery')
output += pd.json.loads(response.body)
output.append(pd.Timestamp.utcnow().time().isoformat())
self.write(pd.json.dumps(output))
class AsynchronousHandler(web.RequestHandler):
@web.asynchronous
def get(self):
client = httpclient.AsyncHTTPClient()
self.output = [pd.Timestamp.utcnow().time().isoformat()]
response = client.fetch('http://localhost:8888/longquery',self.on_response)
def on_response(self, response):
self.output += pd.json.loads(response.body)
self.output.append(pd.Timestamp.utcnow().time().isoformat())
self.write(pd.json.dumps(self.output))
self.finish()
app = web.Application([
("/longquery", LongQueryHandler),
("/synchronous", SynchronousHandler),
("/asynchronous", AsynchronousHandler),
])
server = httpserver.HTTPServer(app)
server.bind(8888)
server.start(100) # forks one process per cpu
ioloop.IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment