Last active
December 29, 2015 05:59
-
-
Save Lothiraldan/7626265 to your computer and use it in GitHub Desktop.
Tornado + yield from = <3
This file contains 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
# http://localhost:8888/?mode=sync | |
http://wikipedia.com code: 200 | |
http://google.com code: 200 | |
http://example.com code: 200 | |
#> time curl http://localhost:8888/\?mode\=sync | |
http://wikipedia.com code: 200<br/>http://google.com code: 200<br/>http://example.com code: 200curl http://localhost:8888/\?mode\=sync 0,01s user 0,00s system 0% cpu 1,106 total | |
# http://localhost:8888/?mode=async | |
http://wikipedia.com code: 200 | |
http://google.com code: 200 | |
http://example.com code: 200 | |
#> time curl http://localhost:8888/\?mode\=async | |
http://wikipedia.com code: 200<br/>http://google.com code: 200<br/>http://example.com code: 200curl http://localhost:8888/\?mode\=async 0,00s user 0,00s system 2% cpu 0,402 total |
This file contains 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
from tornado.ioloop import IOLoop | |
from tornado.gen import coroutine | |
from tornado.httpclient import AsyncHTTPClient, HTTPClient | |
import tornado.web | |
from inspect import isgeneratorfunction | |
class MainHandler(tornado.web.RequestHandler): | |
@coroutine | |
def get(self): | |
urls = ['http://wikipedia.com', 'http://google.com', 'http://example.com'] | |
modes = {'sync': self._get_sync, 'async': self._get_async} | |
mode = self.get_argument('mode', 'sync') | |
method = modes[mode] | |
if isgeneratorfunction(method): | |
result = yield from method(urls) | |
else: | |
result = method(urls) | |
self.write('<br/>'.join(result)) | |
def _get_async(self, urls): | |
body = [] | |
results = yield from self._async(urls) | |
return ('%s code: %s' % (response.request.url, response.code) for response in results) | |
def _get_sync(self, urls): | |
body = [] | |
for url in urls: | |
result = self._sync(url) | |
body.append('%s code: %s' % (url, result.code)) | |
return body | |
def _sync(self, url): | |
http_client = HTTPClient() | |
return http_client.fetch(url) | |
def _async(self, urls): | |
http_client = AsyncHTTPClient() | |
result = yield [http_client.fetch(url) for url in urls] | |
return result | |
application = tornado.web.Application([ | |
(r"/", MainHandler), | |
]) | |
if __name__ == "__main__": | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment