How to understand appengine ndb.tasklet?

From the documentation :

The task of NDB is a piece of code that can work simultaneously with other code. If you write a tasklet, your application can use it a lot, for example, it uses the asynchronous NDB function: it calls a tasklet that returns the Future; later calling the get_result () method of the future result.

I really like the explanation and examples in the document. I can use it, but it’s hard for him to get it right.

For example:

  • Is it possible to place some code inside a function and decorate it as ndb.tasklet? Then it was later used as a function of asynchronous input. Or should it be an RPC application?
  • Does this decorator also work on my pc?
  • This is the same as tasklet for pypy
+7
source share
1 answer

If you look at the implementation of the Future, then it is very similar to the fact that the generator is on python. In fact, it uses the same yield keyword to achieve what it says. Read the introductory comments on tasklets.py for some clarification.

When you use the @tasklet decorator, it creates the future and waits for the value for the wrapped function. If the value is a generator, it adds Future to the event loop. When you yield in the Future, the event loop goes through ALL queued Futures until the Future you want is ready. The concurrency here is that each Future will execute its code until it returns (using raise ndb.Return(...) or the function ends), an exception is thrown, or yield used again. I assume that technically you can use yield in your code to stop this function from running in favor of the cycle loop continuing to work with other futures, but I would suggest that this does not help if you really have a smart use case in mind.

To answer your questions:

  • Technically, yes, but it will not execute asynchronously. When you decorate an unnecessary function with @tasklet, its Future value is calculated and set when this function is called. That is, it goes through the whole function when you call it. If you want to achieve asynchronous operation, you must yield to do what the asynchronous operation does. Typically, in GAE, it will work until the RPC is called.

  • If while working on your computer you mean that dev appserver implements tasklets / Futures, for example GAE, then yes, although this is more accurate with devappserver2 (now by default in the new SDK). I'm actually not 100% sure if local RPC calls will work in parallel when using Futures, but there are futures that go through Futures, whether local or in production. If you want to use Future in your other non-GAE code, then I think you would be better off using Python 3.2 built into the future (or find backport here )

  • It seems that this is not just a comparison. Look at here . The idea is somewhat the same (the scheduler can be compared to eventloop), but the low-level implementation is significantly different.

+14
source

All Articles