U )._TA@sdZddlZddlmZddlmZddlmZddlmZddl m Z dd l m Z dd l m Z dd l mZeZGd d d eZddZddZddZddZGdddeZGdddeZdS)z flask.ctx ~~~~~~~~~ Implements the objects required to keep the context. :copyright: 2010 Pallets :license: BSD-3-Clause N)update_wrapper) HTTPException)BROKEN_PYPY_CTXMGR_EXIT)reraise)_app_ctx_stack)_request_ctx_stack)appcontext_popped)appcontext_pushedc@sHeZdZdZdddZefddZdddZd d Zd d Z d dZ dS)_AppCtxGlobalsaA plain object. Used as a namespace for storing data during an application context. Creating an app context automatically creates this object, which is made available as the :data:`g` proxy. .. describe:: 'key' in g Check whether an attribute is present. .. versionadded:: 0.10 .. describe:: iter(g) Return an iterator over the attribute names. .. versionadded:: 0.10 NcCs|j||S)zGet an attribute by name, or a default value. Like :meth:`dict.get`. :param name: Name of attribute to get. :param default: Value to return if the attribute is not present. .. versionadded:: 0.10 )__dict__getselfnamedefaultrC:\Users\Miouzora\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\flask/ctx.pyr 0s z_AppCtxGlobals.getcCs&|tkr|j|S|j||SdS)a Get and remove an attribute by name. Like :meth:`dict.pop`. :param name: Name of attribute to pop. :param default: Value to return if the attribute is not present, instead of raise a ``KeyError``. .. versionadded:: 0.11 N) _sentinelr poprrrrr;s  z_AppCtxGlobals.popcCs|j||S)a6Get the value of an attribute if it is present, otherwise set and return a default value. Like :meth:`dict.setdefault`. :param name: Name of attribute to get. :param: default: Value to set and return if the attribute is not present. .. versionadded:: 0.11 )r setdefaultrrrrrIs z_AppCtxGlobals.setdefaultcCs ||jkSN)r )ritemrrr __contains__Usz_AppCtxGlobals.__contains__cCs t|jSr)iterr rrrr__iter__Xsz_AppCtxGlobals.__iter__cCs$tj}|dk rd|jjSt|S)Nz)rtopapprobject__repr__)rrrrrr [s z_AppCtxGlobals.__repr__)N)N) __name__ __module__ __qualname____doc__r rrrrrr rrrrr s  r cCstjj||S)aExecutes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one. Example:: @app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object. .. versionadded:: 0.9 )rr_after_request_functionsappend)frrrafter_this_requestbsr(cs6tj}|dkrtd|fdd}t|S)a:A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request or # flask.session like you would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10 Nz|This decorator can only be used at local scopes when a request context is on the stack. For instance within view functions.c s&||W5QRSQRXdSrr)argskwargsr'Zreqctxrrwrappersz-copy_current_request_context..wrapper)rr RuntimeErrorcopyr)r'rr,rr+rcopy_current_request_context{sr/cCs tjdk S)aIf you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as :class:`request` or :class:`g`) for truthness:: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr .. versionadded:: 0.7 N)rrrrrrhas_request_contextsr0cCs tjdk S)zWorks like :func:`has_request_context` but for the application context. You can also just do a boolean check on the :data:`current_app` object instead. .. versionadded:: 0.9 N)rrrrrrhas_app_contextsr1c@s<eZdZdZddZddZefddZdd Zd d Z d S) AppContexta]The application context binds an application object implicitly to the current thread or greenlet, similar to how the :class:`RequestContext` binds request information. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context. cCs&||_|d|_||_d|_dS)Nr)rcreate_url_adapter url_adapterZapp_ctx_globals_classg_refcnt)rrrrr__init__s  zAppContext.__init__cCs:|jd7_ttdr tt|t|jdS)z-Binds the app context to the current context.r exc_clearN) r6hasattrsysr8rpushr sendrrrrrr;s   zAppContext.pushcCspz<|jd8_|jdkr:|tkr.td}|j|W5t}X||ks`td||ft |jdS)zPops the app context.rrz-Popped wrong app context. (%r instead of %r)N) rrr6rr:exc_inforZdo_teardown_appcontextAssertionErrorr r<)rexcrvrrrrs   zAppContext.popcCs ||Srr;rrrr __enter__szAppContext.__enter__cCs&||tr"|dk r"t|||dSr)rrrrexc_type exc_valuetbrrr__exit__s  zAppContext.__exit__N) r!r"r#r$r7r;rrrBrGrrrrr2s   r2c@sxeZdZdZdddZeddZejddZdd Zd d Z d d Z e fddZ ddZ ddZddZddZdS)RequestContextaThe request context contains all request relevant information. It is created at the beginning of the request and pushed to the `_request_ctx_stack` and removed at the end of it. It will create the URL adapter and request object for the WSGI environment provided. Do not attempt to use this class directly, instead use :meth:`~flask.Flask.test_request_context` and :meth:`~flask.Flask.request_context` to create this object. When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (:meth:`~flask.Flask.teardown_request`). The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of ``DEBUG`` mode. By setting ``'flask._preserve_context'`` to ``True`` on the WSGI environment the context will not pop itself at the end of the request. This is used by the :meth:`~flask.Flask.test_client` for example to implement the deferred cleanup functionality. You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in that situation, otherwise your unittests will leak memory. Nc Cs||_|dkr||}||_d|_z||j|_Wn*tk r`}z ||j_W5d}~XYnXd|_||_g|_ d|_ d|_ g|_ dS)NF) rZ request_classrequestr4r3rrouting_exceptionZflashessession_implicit_app_ctx_stack preserved_preserved_excr%)rrenvironrIrKerrrr7s zRequestContext.__init__cCstjjSrrrr5rrrrr5=szRequestContext.gcCs |tj_dSrrQ)rvaluerrrr5AscCs|j|j|jj|j|jdS)a5Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked. .. versionadded:: 0.10 .. versionchanged:: 1.1 The current session object is used instead of reloading the original data. This prevents `flask.session` pointing to an out-of-date object. )rOrIrK) __class__rrIrOrKrrrrr.Es zRequestContext.copyc CsRz"|jjdd}|\|j_|j_Wn*tk rL}z ||j_W5d}~XYnXdS)zZCan be overridden by a subclass to hook into the matching of the request. T)Z return_ruleN)r4matchrIZurl_ruleZ view_argsrrJ)rresultrPrrr match_requestYs zRequestContext.match_requestcCstj}|dk r |jr ||jtj}|dks:|j|jkrZ|j}||j |n |j dt t drxt t||jdkr|jj}||j|j|_|jdkr||j|_|jdk r|dS)z1Binds the request context to the current context.Nr8)rrrMrrNrrZ app_contextr;rLr&r9r:r8rKsession_interfaceZ open_sessionrIZmake_null_sessionr4rV)rrapp_ctxrWrrrr;cs&         zRequestContext.pushc Cs|j}zld}|jstd|_d|_|tkr6t d}|j |t t drTt t|jdd}|dk rp|d}W5t}|rd|jjd<|dk r||||kstd||fXdS) a Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the :meth:`~flask.Flask.teardown_request` decorator. .. versionchanged:: 0.9 Added the `exc` argument. Nzwerkzeug.requestz0Popped wrong request context. (%r instead of %r)Frr8closeT)rLrrrIrOr>rMrNrr:r=rZdo_teardown_requestr9r8getattr)rr?rXr@Z clear_requestZ request_closerrrrs0       zRequestContext.popcCs:|jjds|dk r,|jjr,d|_||_n ||dS)Nzflask._preserve_contextT)rIrOr rZpreserve_context_on_exceptionrMrNr)rr?rrrauto_popszRequestContext.auto_popcCs ||SrrArrrrrBszRequestContext.__enter__cCs&||tr"|dk r"t|||dSr)r[rrrCrrrrGs  zRequestContext.__exit__cCs d|jj|jj|jj|jjfS)Nz<%s '%s' [%s] of %s>)rSr!rIurlmethodrrrrrrr s zRequestContext.__repr__)NN)r!r"r#r$r7propertyr5setterr.rVr;rrr[rBrGr rrrrrHs    + /  rH)r$r: functoolsrZwerkzeug.exceptionsr_compatrrglobalsrrZsignalsr r rrr r(r/r0r1r2rHrrrrs"         F(  2