I
I
Ilya2015-04-02 18:07:44
Python
Ilya, 2015-04-02 18:07:44

How to create an instance of a class asynchronously in Tornado?

More or less figured out (as it seems to me) with asynchrony in a tornado, but when rewriting the synchronous code under a tornado, the following problem arose:
During request processing, instances of various objects are created:

@gen.coroutine
def prepare(self):
  ....
  obj = ObjClass()
  ...

, while queries are executed to the database that we would like to execute asynchronously:
class ObjClass:
  def __init__(self):
    ...
    db.find({...})
    ...

The first thing that came to mind was to add additional initialization in all classes (if not remove __init__ altogether), into which everything that needs to be made asynchronous should be added:
class ObjClass:
  def __init__(self):
    ...

  @gen.coroutine
  def init(self):
    ...
    db.find({...})
    ...

@gen.coroutine
def prepare(self):
  ....
  obj = yield ObjClass().init()
  ...

But I want to write something like:
class ObjClass:
  @gen.coroutine
  def __init__(self):
    ...
    yield db.find({...})
    ...

@gen.coroutine
def prepare(self):
  ....
  obj = yield ObjClass()
  ...

I tried to dig in the direction of metaclasses and redefining __call__, but the expression
yield obj.__init__(*args, **kwargs)
does not seem to work, because __init__ in the class stubbornly does not want to become a generator with
class ObjClass:
  @gen.coroutine
  def __init__(self):
    ...
    yield db.find({...})
    ...

Is there some hidden magic in the interpreter that you can't drag a coroutine through?
How else can you create an instance asynchronously in Tornado?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
un1t, 2015-04-02
@un1t

Apparently you are using some kind of synchronous code to work with the database.
You need to use an asynchronous driver for your tornado base.

A
Andrey K, 2015-04-03
@mututunus

__init__ does not return anything and therefore cannot be a coroutine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question