Skip to content
Myr

ctx.py

This file

Path

flask/ctx.py

179 lines · 6.8 KiB · Python

Last changed by

Break up a circular dependency on shutdownArmin Ronacherbefore adoption7f4c12b

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    flask.ctx4    ~~~~~~~~~56    Implements the objects required to keep the context.78    :copyright: (c) 2011 by Armin Ronacher.9    :license: BSD, see LICENSE for more details.10"""1112from werkzeug.exceptions import HTTPException1314from .globals import _request_ctx_stack15from .module import blueprint_is_module161718class _RequestGlobals(object):19    pass202122def has_request_context():23    """If you have code that wants to test if a request context is there or24    not this function can be used.  For instance if you want to take advantage25    of request information is it's available but fail silently if the request26    object is unavailable.2728    ::2930        class User(db.Model):3132            def __init__(self, username, remote_addr=None):33                self.username = username34                if remote_addr is None and has_request_context():35                    remote_addr = request.remote_addr36                self.remote_addr = remote_addr3738    Alternatively you can also just test any of the context bound objects39    (such as :class:`request` or :class:`g` for truthness)::4041        class User(db.Model):4243            def __init__(self, username, remote_addr=None):44                self.username = username45                if remote_addr is None and request:46                    remote_addr = request.remote_addr47                self.remote_addr = remote_addr4849    .. versionadded:: 0.750    """51    return _request_ctx_stack.top is not None525354class RequestContext(object):55    """The request context contains all request relevant information.  It is56    created at the beginning of the request and pushed to the57    `_request_ctx_stack` and removed at the end of it.  It will create the58    URL adapter and request object for the WSGI environment provided.5960    Do not attempt to use this class directly, instead use61    :meth:`~flask.Flask.test_request_context` and62    :meth:`~flask.Flask.request_context` to create this object.6364    When the request context is popped, it will evaluate all the65    functions registered on the application for teardown execution66    (:meth:`~flask.Flask.teardown_request`).6768    The request context is automatically popped at the end of the request69    for you.  In debug mode the request context is kept around if70    exceptions happen so that interactive debuggers have a chance to71    introspect the data.  With 0.4 this can also be forced for requests72    that did not fail and outside of `DEBUG` mode.  By setting73    ``'flask._preserve_context'`` to `True` on the WSGI environment the74    context will not pop itself at the end of the request.  This is used by75    the :meth:`~flask.Flask.test_client` for example to implement the76    deferred cleanup functionality.7778    You might find this helpful for unittests where you need the79    information from the context local around for a little longer.  Make80    sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in81    that situation, otherwise your unittests will leak memory.82    """8384    def __init__(self, app, environ):85        self.app = app86        self.request = app.request_class(environ)87        self.url_adapter = app.create_url_adapter(self.request)88        self.g = _RequestGlobals()89        self.flashes = None90        self.session = None9192        # indicator if the context was preserved.  Next time another context93        # is pushed the preserved context is popped.94        self.preserved = False9596        self.match_request()9798        # XXX: Support for deprecated functionality.  This is doing away with99        # Flask 1.0100        blueprint = self.request.blueprint101        if blueprint is not None:102            # better safe than sorry, we don't want to break code that103            # already worked104            bp = app.blueprints.get(blueprint)105            if bp is not None and blueprint_is_module(bp):106                self.request._is_old_module = True107108    def match_request(self):109        """Can be overridden by a subclass to hook into the matching110        of the request.111        """112        try:113            url_rule, self.request.view_args = \114                self.url_adapter.match(return_rule=True)115            self.request.url_rule = url_rule116        except HTTPException, e:117            self.request.routing_exception = e118119    def push(self):120        """Binds the request context to the current context."""121        # If an exception ocurrs in debug mode or if context preservation is122        # activated under exception situations exactly one context stays123        # on the stack.  The rationale is that you want to access that124        # information under debug situations.  However if someone forgets to125        # pop that context again we want to make sure that on the next push126        # it's invalidated otherwise we run at risk that something leaks127        # memory.  This is usually only a problem in testsuite since this128        # functionality is not active in production environments.129        top = _request_ctx_stack.top130        if top is not None and top.preserved:131            top.pop()132133        _request_ctx_stack.push(self)134135        # Open the session at the moment that the request context is136        # available. This allows a custom open_session method to use the137        # request context (e.g. flask-sqlalchemy).138        self.session = self.app.open_session(self.request)139        if self.session is None:140            self.session = self.app.make_null_session()141142    def pop(self):143        """Pops the request context and unbinds it by doing that.  This will144        also trigger the execution of functions registered by the145        :meth:`~flask.Flask.teardown_request` decorator.146        """147        self.preserved = False148        self.app.do_teardown_request()149        rv = _request_ctx_stack.pop()150        assert rv is self, 'Popped wrong request context.  (%r instead of %r)' \151            % (rv, self)152153        # get rid of circular dependencies at the end of the request154        # so that we don't require the GC to be active.155        rv.request.environ['werkzeug.request'] = None156157    def __enter__(self):158        self.push()159        return self160161    def __exit__(self, exc_type, exc_value, tb):162        # do not pop the request stack if we are in debug mode and an163        # exception happened.  This will allow the debugger to still164        # access the request object in the interactive shell.  Furthermore165        # the context can be force kept alive for the test client.166        # See flask.testing for how this works.167        if self.request.environ.get('flask._preserve_context') or \168           (tb is not None and self.app.preserve_context_on_exception):169            self.preserved = True170        else:171            self.pop()172173    def __repr__(self):174        return '<%s \'%s\' [%s] of %s>' % (175            self.__class__.__name__,176            self.request.url,177            self.request.method,178            self.app.name179        )