Skip to content

Instantly share code, notes, and snippets.

@cedricporter
Last active December 29, 2015 05:39
Show Gist options
  • Save cedricporter/7623694 to your computer and use it in GitHub Desktop.
Save cedricporter/7623694 to your computer and use it in GitHub Desktop.
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.gen
from tornado import httpclient
@tornado.gen.coroutine
def fetch_json(url):
response = yield httpclient.AsyncHTTPClient().fetch(url)
raise tornado.gen.Return(tornado.json_decode(response.body))
def my_get(callback):
def my_cb(*args, **kwargs):
print args
print kwargs
callback(*args, **kwargs)
print '1' * 100
http_client = httpclient.AsyncHTTPClient()
return http_client.fetch("http://everet.org/", my_cb)
@tornado.gen.coroutine
def my_get2():
print '1' * 100
http_client = httpclient.AsyncHTTPClient()
resp = yield http_client.fetch("http://everet.org/")
raise tornado.gen.Return(resp)
def check_data(method):
print 'check_data'
@tornado.gen.coroutine
def wrapped(*args, **kwargs):
http_client = httpclient.AsyncHTTPClient()
resp = yield http_client.fetch("http://hua.bz/")
if "Stupid ET" in resp.body:
yield method(*args, **kwargs)
print 'check_data return'
return wrapped
class MainHandler(tornado.web.RequestHandler):
@check_data
@tornado.gen.coroutine
def get(self):
print '0' * 100
# response = yield tornado.gen.Task(my_get)
response = yield my_get2()
self.write(response.body)
class TextHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
def cb(it, callback):
try:
value = it.next()
except StopIteration:
value = None
callback(value)
it = self.generate_text(1000)
while True:
response = yield tornado.gen.Task(cb, it)
if response:
self.write(response)
else:
break
self.finish()
def generate_text(self, n):
for x in xrange(n):
if not x % 15:
yield "FizzBuzz\n"
elif not x % 5:
yield "Buzz\n"
elif not x % 3:
yield "Fizz\n"
else:
yield "%s\n" % x
application = tornado.web.Application([
(r"/", MainHandler),
(r"/text/", TextHandler),
], debug=True)
http_server = tornado.httpserver.HTTPServer(application)
http_server.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