+-
python – 使用带协程的上下文管理器
此代码不起作用

from contextlib import contextmanager                                                     
import tornado.ioloop                                                                     
import tornado.web                                                                        
from tornado import gen                                                                   
from tornado.httpclient import AsyncHTTPClient                                            


@contextmanager                                                                           
def hello():                                                                              
    print("hello in")                                                                     
    yield                                                                                 
    print("hello out")                                                                    


class MainHandler(tornado.web.RequestHandler):                                            
    @gen.coroutine                                                                        
    def get(self):                                                                        
        client = AsyncHTTPClient()                                                        
        with hello():                                                                     
            result = yield client.fetch("http://localhost")                               
        return "Hello "+str(result)                                                       

app = tornado.web.Application([('/', MainHandler)])                                       
app.listen(12345)                                                                         
tornado.ioloop.IOLoop.current().start()                                                   

并且它不起作用的原因是上下文管理器屈服和协程屈服在它们的行为上是不相容的.

您是否确认实现此目的的唯一方法是最后使用try(如果必须在许多地方使用上下文管理器代码,则特别烦人).也许有一个我不知道的微妙技巧?谷歌搜索没有帮助.

编辑

这是我得到的输出

(venv) sborini@Mac-34363bd19f52:tornado$python test.py 
hello in
ERROR:tornado.application:Uncaught exception GET / (::1)
HTTPServerRequest(protocol='http', host='localhost:12345', method='GET', uri='/', version='HTTP/1.1', remote_ip='::1', headers={'Upgrade-Insecure-Requests': '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36', 'Accept-Language': 'en-US,en;q=0.8,it;q=0.6', 'Connection': 'keep-alive', 'Host': 'localhost:12345', 'Accept-Encoding': 'gzip, deflate, sdch'})
Traceback (most recent call last):
  File "/Users/sborini/Work/Experiments/tornado/venv/lib/python3.4/site-packages/tornado/web.py", line 1445, in _execute
    result = yield result
  File "/Users/sborini/Work/Experiments/tornado/venv/lib/python3.4/site-packages/tornado/gen.py", line 1008, in run
    value = future.result()
  File "/Users/sborini/Work/Experiments/tornado/venv/lib/python3.4/site-packages/tornado/concurrent.py", line 232, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
  File "/Users/sborini/Work/Experiments/tornado/venv/lib/python3.4/site-packages/tornado/gen.py", line 1014, in run
    yielded = self.gen.throw(*exc_info)
  File "test.py", line 20, in get
    result = yield client.fetch("http://localhost")
  File "/Users/sborini/Work/Experiments/tornado/venv/lib/python3.4/site-packages/tornado/gen.py", line 1008, in run
    value = future.result()
  File "/Users/sborini/Work/Experiments/tornado/venv/lib/python3.4/site-packages/tornado/concurrent.py", line 232, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
ConnectionRefusedError: [Errno 61] Connection refused
ERROR:tornado.access:500 GET / (::1) 5.04ms

关键是我永远不会得到你好的消息.我希望,一旦fetch产生未来和未来的错误,我将返回到屈服点,获得异常,并离开上下文,触发print(‘hello out’).

请注意,如果我只是尝试一下,我确实会打招呼:最后:围绕收益率

最佳答案
代码的结构是正确的,并且可以通过这种方式混合上下文管理器和协同程序. @contextmanager和@coroutine装饰器在装饰函数中分别赋予它们自己的含义,但它们保持独立.

如上所述,如果对http:// localhost的提取成功(或者如果将其更改为指向可用的服务器),则此代码将打印“hello in”和“hello out”,但它不会打印“hello out” “如果fetch引发异常.要做到这一点,你需要在装饰器中使用try / finally:

@contextmanager
def hello():                                                                              
    print("hello in")                                                                     
    try:
        yield                                                                                 
    finally:
        print("hello out")   

此代码中的另一个错误是您从get()返回一个值. get()的返回值被忽略;在Tornado中产生输出你必须调用self.write()(或finish()或render()).

点击查看更多相关文章

转载注明原文:python – 使用带协程的上下文管理器 - 乐贴网