當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。