python 使用StackContext在Tornado中全局存储请求数据的示例。请参阅https://groups.google.com/d/msg/python-tornado/8izNLhYj

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用StackContext在Tornado中全局存储请求数据的示例。请参阅https://groups.google.com/d/msg/python-tornado/8izNLhYj相关的知识,希望对你有一定的参考价值。

import threading


class ThreadRequestContext(object):
    """A context manager that saves some per-thread state globally.
    Intended for use with Tornado's StackContext.
    
    Provide arbitrary data as kwargs upon creation,
    then use ThreadRequestContext.data to access it.
    """
    
    _state = threading.local()
    _state.data = {}

    class __metaclass__(type):
        # property() doesn't work on classmethods,
        #  see http://stackoverflow.com/q/128573/1231454
        @property
        def data(cls):
            if not hasattr(cls._state, 'data'):
               return {}
            return cls._state.data

    def __init__(self, **data):
        self._data = data

    def __enter__(self):
        self._prev_data = self.__class__.data
        self.__class__._state.data = self._data

    def __exit__(self, *exc):
        self.__class__._state.data = self._prev_data
        del self._prev_data
        return False
import tornado


class RequestContextHandler(tornado.web.RequestHandler):
    
    def _execute(self, transforms, *args, **kwargs):
        # following the example of:
        #  https://github.com/bdarnell/tornado_tracing/blob/master/tornado_tracing/recording.py
        
        global_data = {}  # add whatever here, e.g. self.request

        with tornado.stack_context.StackContext(functools.partial(ThreadRequestContext, **global_data)):
            super(RequestContextHandler, self)._execute(transforms, *args, **kwargs)
            
# elsewhere, use ThreadRequestContext.data => a dict

以上是关于python 使用StackContext在Tornado中全局存储请求数据的示例。请参阅https://groups.google.com/d/msg/python-tornado/8izNLhYj的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有浏览器的情况下在 python 中使用 Tor?

在 python 中使用 urllib2 和 Tor 拒绝连接

在 Python 上使用 Selenium 来操作 Tor。由于未知原因不起作用

使用Python通过Tor(SOCKS5)发送UDP请求

使用 TOR 运行 python 脚本

使用python连接到tor上的.onion网站?