mikemaccana
mikemaccana

Reputation: 123490

Simplest tornado.gen example

I am trying to use Tornado's sync-style 'gen' tool to run a simple echo function, in a non-blocking style:

import tornado.web
import tornado.gen
import logging

def echo(message):
    return message

@tornado.gen.engine
def runme():
    response = yield tornado.gen.Task(echo, 'this is a message')
    logging.warn(response)

runme()

As far as I can tell this code isn't significantly different to the demo code in the docs, minus the unnecessary request handler stuff - I'm not handling any HTTP requests, AFAICT that's orthagonal to running something asynchronously. Yet this always fails with:

Traceback (most recent call last):
  File "./server.py", line 46, in <module>
runme()
TypeError: wrapper() takes at least 1 argument (0 given)

Exactly where am I missing the argument? How can I make Tornado run this function asynchronously?

Upvotes: 1

Views: 4023

Answers (1)

mikemaccana
mikemaccana

Reputation: 123490

Task doesn't actually make a callback for the function being run, and start the callback when the function returns, as I originally thought.

I need to create a callback in the task being run myself, and invoke it, i.e.:

import tornado.web
import tornado.gen
import logging

def echo(message, callback=None):
    callback(message)

@tornado.gen.engine
def runme():
    response = yield tornado.gen.Task(echo, 'this is a message')
    logging.warn(response)

runme()

Upvotes: 2

Related Questions