Created
August 3, 2017 02:01
-
-
Save rsj217/861df566ef8f269aad0830989fe64c17 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env | |
# coding: utf-8 | |
import asyncio | |
import requests | |
import tornado.gen as gen | |
import tornado.httpclient as httpclient | |
import tornado.httpserver as httpserver | |
import tornado.options as options | |
import tornado.platform.asyncio as tornado_asyncio | |
import tornado.web as web | |
import uvloop | |
options.parse_command_line() | |
class IndexHandler(web.RequestHandler): | |
def get(self): | |
self.finish("It works") | |
class SleepHandler(web.RequestHandler): | |
async def get(self): | |
print("hello tornado") | |
await asyncio.sleep(5) | |
self.write('It works!') | |
class AsyncHttpHandler(web.RequestHandler): | |
async def get(self): | |
url = 'http://127.0.0.1:5000/' | |
client = httpclient.AsyncHTTPClient() | |
resp = await client.fetch(url) | |
print(resp.body) | |
self.finish(resp.body) | |
class GenHttpHandler(web.RequestHandler): | |
@gen.coroutine | |
def get(self): | |
url = 'http://127.0.0.1:5000/' | |
client = httpclient.AsyncHTTPClient() | |
resp = yield client.fetch(url) | |
print(resp.body) | |
self.finish(resp.body) | |
class SyncHttpHandler(web.RequestHandler): | |
async def get(self): | |
url = 'http://127.0.0.1:5000/' | |
resp = requests.get(url) | |
print(resp.text) | |
self.finish(resp.text) | |
class App(web.Application): | |
def __init__(self): | |
settings = { | |
'debug': True | |
} | |
super(App, self).__init__( | |
handlers=[ | |
(r'/', IndexHandler), | |
(r'/async', AsyncHttpHandler), | |
(r'/gen', GenHttpHandler), | |
(r'/sync', SyncHttpHandler), | |
(r'/sleep', SleepHandler), | |
], | |
**settings) | |
if __name__ == '__main__': | |
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) | |
tornado_asyncio.AsyncIOMainLoop().install() | |
app = App() | |
server = httpserver.HTTPServer(app, xheaders=True) | |
server.listen(5030) | |
asyncio.get_event_loop().run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This piece of code helped me a lot. Just wanted to say that in Tornado 5.0 AsyncIOMainLoop is deprecated. But the code above runs ok just commenting the line tornado_asyncio.AsyncIOMainLoop().install()