当前位置: 首页>>代码示例>>Python>>正文


Python local.LocalProxy方法代码示例

本文整理汇总了Python中werkzeug.local.LocalProxy方法的典型用法代码示例。如果您正苦于以下问题:Python local.LocalProxy方法的具体用法?Python local.LocalProxy怎么用?Python local.LocalProxy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug.local的用法示例。


在下文中一共展示了local.LocalProxy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_token

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def add_token(request: LocalProxy, session: Session) -> str:
    """
    Create a new token for the user or return a
    valid existing token to the user.
    """
    token = None
    id_ = int(request.authorization['username'])
    try:
        token = session.query(Token).filter(Token.user_id == id_).one()
        if not token.is_valid():
            update_token = '%030x' % randrange(16**30)
            token.id = update_token
            token.timestamp = datetime.now()
            session.commit()
    except NoResultFound:
        token = '%030x' % randrange(16**30)
        new_token = Token(user_id=id_, id=token)
        session.add(new_token)
        session.commit()
        return token
    return token.id 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,代码来源:user.py

示例2: __init__

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def __init__(self, signing_secret, endpoint, emitter, server):
        self.signing_secret = signing_secret
        self.emitter = emitter
        self.endpoint = endpoint
        self.package_info = self.get_package_info()

        # If a server is passed in, bind the event handler routes to it,
        # otherwise create a new Flask instance.
        if server:
            if isinstance(server, (Flask, Blueprint, LocalProxy)):
                self.bind_route(server)
            else:
                raise TypeError("Server must be an instance of Flask, Blueprint, or LocalProxy")
        else:
            Flask.__init__(self, __name__)
            self.bind_route(self) 
开发者ID:slackapi,项目名称:python-slack-events-api,代码行数:18,代码来源:server.py

示例3: send_email

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def send_email(template, recipient, subject, **kwargs):
    # Convert database model instances to serializable dicts
    new_kwargs = {}
    for k, v in kwargs.items():
        if isinstance(v, UuidMixin):
            new_kwargs[k] = {
                'clz': type(v).__name__,
                'uuid': v.uuid,
            }
        elif isinstance(v, LocalProxy) and isinstance(v._get_current_object(), UuidMixin):
            new_kwargs[k] = {
                'clz': type(v._get_current_object()).__name__,
                'uuid': v.uuid,
            }
        else:
            new_kwargs[k] = v

    if current_app.config.get('RQ_ENABLED'):
        # Enqueue the message to send by the RQ worker
        send_email_queued.queue(template, recipient, subject, **new_kwargs)
    else:
        # Do the work during the request
        send_email_queued(template, recipient, subject, **new_kwargs) 
开发者ID:RagtagOpen,项目名称:nomad,代码行数:25,代码来源:__init__.py

示例4: task

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def task(*args, **kwargs):
    """Register the decorated method as a celery task; use this just like
    app.task."""
    def inner(**kwargs):
        def wrap(fn):
            _defined_tasks[fn] = kwargs
            return LocalProxy(lambda: current_app.celery_tasks[fn])
        return wrap
    # remainder of this function is adapted from celery/app/base.py
    # (BSD-licensed)
    if len(args) == 1:
        if callable(args[0]):
            return inner(**kwargs)(*args)
        raise TypeError('argument 1 to @task() must be a callable')
    if args:
        raise TypeError(
            '@db.task() takes exactly 1 argument ({0} given)'.format(
                sum([len(args), len(kwargs)])))
    return inner(**kwargs) 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:21,代码来源:celery.py

示例5: flask_request_to_dict_request

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def flask_request_to_dict_request(flask_request: LocalProxy) -> dict:
    """Convert flask request to dict request."""
    urllib_url = urlparse(flask_request.url)

    return {
        'headers': dict(flask_request.headers),
        'method': flask_request.method,
        'url': {
            'scheme': urllib_url.scheme,
            'netloc': urllib_url.netloc,
            'path': urllib_url.path,
            'params': urllib_url.params,
            'query': dict(parse_qsl(urllib_url.query)),
            'fragment': urllib_url.fragment
        },
        'body': dict(flask_request.json) if flask_request.json else {}
    } 
开发者ID:koursaros-ai,项目名称:nboost,代码行数:19,代码来源:translators.py

示例6: check_nonce

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def check_nonce(request: LocalProxy, session: Session) -> bool:
    """check validity of nonce passed by the user."""
    try:
        id_ = request.headers['X-Authentication']
        nonce = session.query(Nonce).filter(Nonce.id == id_).one()
        present = datetime.now()
        present = present - nonce.timestamp
        session.delete(nonce)
        session.commit()
        if present > timedelta(0, 0, 0, 0, 1, 0, 0):
            return False
    except BaseException:
        return False
    return True 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:16,代码来源:user.py

示例7: check_token

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def check_token(request: LocalProxy, session: Session) -> bool:
    """
    check validity of the token passed by the user.
    """
    token = None
    try:
        id_ = request.headers['X-Authorization']
        token = session.query(Token).filter(Token.id == id_).one()
        if not token.is_valid():
            token.delete()
            return False
    except BaseException:
        return False
    return True 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:16,代码来源:user.py

示例8: check_authorization

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def check_authorization(request: LocalProxy, session: Session) -> bool:
    """Check if the request object has the correct authorization."""
    auth = request.authorization
    if check_nonce(request, session):
        return authenticate_user(auth.username, auth.password, session)
    return False 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:8,代码来源:user.py

示例9: context_manager

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def context_manager(self):
        """LocalProxy refering to the app's instance of the  :class: `ContextManager`.

        Interface for adding and accessing contexts and their parameters
        """
        return getattr(
            _app_ctx_stack.top, "_assist_context_manager", ContextManager(self)
        ) 
开发者ID:treethought,项目名称:flask-assistant,代码行数:10,代码来源:core.py

示例10: send_mail

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def send_mail(subject, recipient, template, **context):
    """Send an email.

    :param subject: Email subject
    :param recipient: Email recipient
    :param template: The name of the email template
    :param context: The context to render the template with
    """

    context.setdefault("security", _security)
    context.update(_security._run_ctx_processor("mail"))

    body = None
    html = None
    ctx = ("security/email", template)
    if config_value("EMAIL_PLAINTEXT"):
        body = _security.render_template("%s/%s.txt" % ctx, **context)
    if config_value("EMAIL_HTML"):
        html = _security.render_template("%s/%s.html" % ctx, **context)

    sender = _security.email_sender
    if isinstance(sender, LocalProxy):
        sender = sender._get_current_object()

    _security._mail_util.send_mail(
        template, subject, recipient, str(sender), body, html, context.get("user", None)
    ) 
开发者ID:Flask-Middleware,项目名称:flask-security,代码行数:29,代码来源:utils.py

示例11: is_local_proxy

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def is_local_proxy(obj) -> bool:
    return isinstance(obj, (WerkzeugLocalProxy, QuartLocalProxy)) 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:4,代码来源:_compat.py

示例12: __call__

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def __call__(self):
        def _lookup():
            rv = self.top
            if rv is None:
                raise RuntimeError("object unbound")
            return rv

        return LocalProxy(_lookup) 
开发者ID:ctpbee,项目名称:ctpbee,代码行数:10,代码来源:proxy.py

示例13: stream_proxy

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def stream_proxy(original):
    def p():
        frame = inspect.currentframe()
        while frame:
            if frame.f_code == ThreadingMixIn.process_request_thread.__code__:
                return fake_stream()
            frame = frame.f_back
        return thread_proxies.get(currentThread().ident,
                                  original)

    return LocalProxy(p) 
开发者ID:alexmojaki,项目名称:executing,代码行数:13,代码来源:ipython.py

示例14: send_mail_async

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def send_mail_async(msg):
    if isinstance(msg.sender, LocalProxy):
        msg.sender = msg.sender._get_current_object()
    return send_mail_async_task.delay(msg) 
开发者ID:briancappello,项目名称:flask-react-spa,代码行数:6,代码来源:extension.py

示例15: freeze

# 需要导入模块: from werkzeug import local [as 别名]
# 或者: from werkzeug.local import LocalProxy [as 别名]
def freeze(object_or_proxy):
    """Get current object of `object_or_proxy` if it is LocalProxy"""
    if isinstance(object_or_proxy, LocalProxy):
        return object_or_proxy._get_current_object()
    return object_or_proxy 
开发者ID:Hardtack,项目名称:Flask-aiohttp,代码行数:7,代码来源:util.py


注:本文中的werkzeug.local.LocalProxy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。