Created
December 30, 2014 23:09
-
-
Save luismasuelli/8df7acea0cd4d228af79 to your computer and use it in GitHub Desktop.
Ejemplo de Tornado con schedulear asincronicamente (lanzar "paralelamente") una tarea en forma de corrutina.
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
import tornado.ioloop | |
import tornado.web | |
import tornado.websocket | |
import tornado.gen | |
clients = [] | |
class IndexHandler(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
def get(request): | |
request.render("index.html") | |
class WebSocketChatHandler(tornado.websocket.WebSocketHandler): | |
def open(self, *args): | |
print("open", "WebSocketChatHandler") | |
clients.append(self) | |
def check_origin(self, origin): | |
return True | |
@tornado.gen.coroutine | |
def on_message(self, message): | |
for client in clients: | |
client.write_message(message) | |
@tornado.gen.coroutine | |
def myroutine(m): | |
""" | |
Esta rutina es lanzada asincronamente. | |
En este caso tengo como ejemplo solamente un punto de yield que es inmediato. | |
Si realmente tuviera un future que se que va a resolverse, "cedo" ese future | |
(el ejemplo no seria significativamente distinto). | |
Para lanzarlo asincronicamente llamo a spawn_callback(myroutine, *a, **kwa) | |
siendo *a y **kwa los parametros que le tengo que pasar a dicha rutina. | |
Cabe recordar que esta no es una rutina normal, sino una corrutina. | |
:param m: | |
:return: | |
""" | |
print "mensaje: " | |
c = (yield tornado.gen.maybe_future(123123123)) | |
print ("mensaje", m, c) | |
tornado.ioloop.IOLoop.instance().spawn_callback(myroutine, message) | |
def on_close(self): | |
clients.remove(self) | |
app = tornado.web.Application([(r'/chat', WebSocketChatHandler), (r'/', IndexHandler)]) | |
app.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