相关疑难解决方法(0)

龙卷风协程

我正在尝试学习龙卷风协同程序,但我使用下面的代码有错误.

Traceback (most recent call last):
  File "D:\projekty\tornado\env\lib\site-packages\tornado\web.py", line 1334, in _execute
    result = yield result
  File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 628, in run
    value = future.result()
  File "D:\projekty\tornado\env\lib\site-packages\tornado\concurrent.py", line 109, in result
    raise_exc_info(self._exc_info)
  File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 631, in run
    yielded = self.gen.throw(*sys.exc_info())
  File "index.py", line 20, in get
    x = yield 'test'
  File "D:\projekty\tornado\env\lib\site-packages\tornado\gen.py", line 628, in run
    value = future.result()
  File "D:\projekty\tornado\env\lib\site-packages\tornado\concurrent.py", line 111, in result
    raise self._exception
BadYieldError: yielded unknown object 'test'
Run Code Online (Sandbox Code Playgroud)

码:

from tornado.ioloop import IOLoop
from tornado.web …
Run Code Online (Sandbox Code Playgroud)

python tornado

13
推荐指数
1
解决办法
1万
查看次数

Python Tornado - 混淆了如何将阻塞函数转换为非阻塞函数

假设我有一个长时间运行的功能:

def long_running_function():
    result_future = Future()
    result = 0
    for i in xrange(500000):
        result += i
    result_future.set_result(result)
    return result_future
Run Code Online (Sandbox Code Playgroud)

我在一个处理程序中有一个get函数,它使用for循环的上述结果打印用户,该循环将添加xrange中的所有数字:

@gen.coroutine
def get(self):
    print "start"

    self.future = long_running_function()
    message = yield self.future
    self.write(str(message))

    print "end"
Run Code Online (Sandbox Code Playgroud)

如果我同时在两个Web浏览器上运行上面的代码,我得到:

开始

结束

开始

结束

这似乎是封锁的.根据我的理解,@gen.coroutineyield语句不会阻止get函数中的IOLoop,但是,如果任何函数在阻塞的协同例程中,那么它会阻塞IOLoop.

因此,我做的另一件事是将其long_running_function转换为回调,并使用yield gen.Task替代.

@gen.coroutine
def get(self):
    print "start"

    self.future = self.long_running_function
    message = yield gen.Task(self.future, None)
    self.write(str(message))

    print "end"

def long_running_function(self, arguments, callback):
    result = 0
    for i in xrange(50000000):
        result += …
Run Code Online (Sandbox Code Playgroud)

python tornado

9
推荐指数
1
解决办法
1857
查看次数

标签 统计

python ×2

tornado ×2