MCPcopy
hub / github.com/pallets/flask / copy_current_request_context

Function copy_current_request_context

src/flask/ctx.py:155–193  ·  view source on GitHub ↗

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 inc

(f: F)

Source from the content-addressed store, hash-verified

153
154
155def copy_current_request_context(f: F) -> F:
156 """A helper function that decorates a function to retain the current
157 request context. This is useful when working with greenlets. The moment
158 the function is decorated a copy of the request context is created and
159 then pushed when the function is called. The current session is also
160 included in the copied request context.
161
162 Example::
163
164 import gevent
165 from flask import copy_current_request_context
166
167 @app.route('/')
168 def index():
169 @copy_current_request_context
170 def do_some_work():
171 # do some work here, it can access flask.request or
172 # flask.session like you would otherwise in the view function.
173 ...
174 gevent.spawn(do_some_work)
175 return 'Regular response'
176
177 .. versionadded:: 0.10
178 """
179 ctx = _cv_request.get(None)
180
181 if ctx is None:
182 raise RuntimeError(
183 "'copy_current_request_context' can only be used when a"
184 " request context is active, such as in a view function."
185 )
186
187 ctx = ctx.copy()
188
189 def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
190 with ctx:
191 return ctx.app.ensure_sync(f)(*args, **kwargs)
192
193 return update_wrapper(wrapper, f) # type: ignore[return-value]
194
195
196def has_request_context() -> bool:

Callers

nothing calls this directly

Calls 2

copyMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected