Created
April 1, 2016 21:06
-
-
Save BibMartin/ac4a80b6559d205e56eb8c06ba61df93 to your computer and use it in GitHub Desktop.
Asynchronous service with tornado
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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