[英]Does python tornado RequestHandler coroutine safe?
As we know, in threading, we have a concept call thread-safe . 众所周知,在线程处理中,我们有一个概念称为thread-safe 。
An when I use tornado coroutine, I don't know whether the self of the RequestHandler coroutine safe of not. 当我使用龙卷风协程时,我不知道RequestHandler协程的自身是否安全。
Here is my code: 这是我的代码:
class IndexHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
self.write("Kingsoft API.")
self.abc = 2
yield self.gener()
self.write(self.k)
print self.k
self.write("Kingsoft API.")
return
@tornado.gen.coroutine
def gener(self):
http_client = AsyncHTTPClient()
self.k = str(int(time.time()*100000))
response = yield http_client.fetch('http://127.0.0.1:8000/')
Another question is, does my code would work expectantly? 另一个问题是,我的代码是否可以正常工作?
Third other question is, I only can use self to pass parameters and return values, but it's so ugly. 第三个问题是,我只能使用self来传递参数和返回值,但这很丑陋。 If I would love to use the AsyncHTTPClient inside some function but not in a callback way, do I have some other nice methods to do?
如果我想在某个函数中使用AsyncHTTPClient而不是通过回调的方式使用,我还有其他好方法吗?
Your code is in a "critical section" between "yield" statements -- you cannot be interrupted unless you execute "yield". 您的代码位于“ yield”语句之间的“关键部分”中-除非执行“ yield”,否则您不会被打断。 So you don't need to worry about accessing "self" or any other value in between yields.
因此,您无需担心在收益率之间访问“自身”或任何其他值。
Parameter passing works normally with coroutines, but to return a value (in Python 2) raise gen.Return: 参数传递通常与协程一起工作,但是要返回一个值(在Python 2中为),请提高gen。
class IndexHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
self.write("Kingsoft API.")
k = yield self.fn(2)
self.write(k)
@tornado.gen.coroutine
def fn(self, arg):
k = 2 * arg
raise tornado.gen.Return(k)
In Python 3.3+ a simple "return k" also works. 在Python 3.3+中,也可以使用简单的“ return k”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.