I know that my question looks to broad, but I hope the answer on this question will give me correct direction what to read on. I am new to Tornado framework, basically I am new to Python. I am looking into this project: Could you please explain me a few lines of code:
@gen.coroutine
def get_me(self):
raise gen.Return((yield self._api.get_me()))
@gen.coroutine
annotation is for?raise
keyword is used for exceptions, isn't it? Why we use it here?generator
. Is the concept of Tornado framework to use generators. What is the reason? Coroutines provide an easier way to work in an asynchronous environment than chaining callbacks. Code using coroutines is technically asynchronous, but it is written as a single generator instead of a collection of separate functions.
In Python, coroutines are similar to generators but with few extra methods and slight changes in how we use yield statements. Generators produce data for iteration while coroutines can also consume data. whatever value we send to coroutine is captured and returned by (yield) expression.
@gen
is a decorator, it will modify the function below it at definition.raise
to return values and will catch it with except gen.Return
(I find it ugly but it works).Following the Tornado documentation, I found that the general way to ensure async behavior is by the use of event loop and callback functions.
But using callbacks is syntactically difficult and kind of confusing.
So the developers of tornado came up with the use of decorators(just like flask,cherrypy etc).
gen.py
module under which they define the coroutine decorator. It's really an elegant way to ensure concurrency in Tornado.raise
is to handle exception. I find it quite easy as it simply returns except gen.Return
.generators
simply it's easy to use.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With