Skip to content
Myr

Added flask.copy_current_request_context which simplies working with greenlets

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 0faed95 · Browse files · 7 files+272 added−114 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+272 added−114 removed

  • other:+272 added−114 removed

7 files+272 added−114 removed

modified:docs/api.rst+2 added
278 unmodified lines
279 This is a proxy. See :ref:`notes-on-proxies` for more information.280281.. autofunction:: has_request_context282283.. autofunction:: copy_current_request_context284285.. autofunction:: has_app_context286287.. autofunction:: url_for288
420 unmodified lines
modified:flask/testsuite/basic.py+1 added-109 removed
664 unmodified lines
665 self.assert_('This was submitted: "index.txt"' in str(e))666 else:667 self.fail('Expected exception')668669 def test_teardown_on_pop(self):670 buffer = []671 app = flask.Flask(__name__)672 @app.teardown_request673 def end_of_request(exception):674 buffer.append(exception)675676 ctx = app.test_request_context()677 ctx.push()678 self.assert_equal(buffer, [])679 ctx.pop()680 self.assert_equal(buffer, [None])681669 def test_response_creation(self):670 app = flask.Flask(__name__)671 @app.route('/unicode')672 def from_unicode():
134 unmodified lines
807 def test_request_locals(self):808 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')809 self.assertFalse(flask.g)810824 def test_proper_test_request_context(self):825 app = flask.Flask(__name__)826 app.config.update(827 SERVER_NAME='localhost.localdomain:5000'828 )829830 @app.route('/')831 def index():832 return None833834 @app.route('/', subdomain='foo')835 def sub():836 return None837838 with app.test_request_context('/'):839 self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')840841 with app.test_request_context('/'):842 self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')843844 try:845 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):846 pass847 except Exception, e:848 self.assert_(isinstance(e, ValueError))849 self.assert_equal(str(e), "the server name provided " +850 "('localhost.localdomain:5000') does not match the " + \851 "server name from the WSGI environment ('localhost')")852853 try:854 app.config.update(SERVER_NAME='localhost')855 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):856 pass857 except ValueError, e:858 raise ValueError(859 "No ValueError exception should have been raised \"%s\"" % e860 )861862 try:863 app.config.update(SERVER_NAME='localhost:80')864 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):865 pass866 except ValueError, e:867 raise ValueError(868 "No ValueError exception should have been raised \"%s\"" % e869 )870811 def test_test_app_proper_environ(self):812 app = flask.Flask(__name__)813 app.config.update(814 SERVER_NAME='localhost.localdomain:5000'
136 unmodified lines
951952 values = dict()953 app.inject_url_defaults('foo.bar.baz.view', values)954 expected = dict(page='login')1015 self.assert_equal(values, expected) 955 self.assert_equal(values, expected)956957 with app.test_request_context('/somepage'):958 url = flask.url_for('foo.bar.baz.view')959 expected = '/login'
106 unmodified lines
1066 self.assert_(flask._request_ctx_stack.top is None)1067 self.assert_(flask._app_ctx_stack.top is None)106810691130class ContextTestCase(FlaskTestCase):11311132 def test_context_binding(self):1133 app = flask.Flask(__name__)1134 @app.route('/')1135 def index():1136 return 'Hello %s!' % flask.request.args['name']1137 @app.route('/meh')1138 def meh():1139 return flask.request.url11401141 with app.test_request_context('/?name=World'):1142 self.assert_equal(index(), 'Hello World!')1143 with app.test_request_context('/meh'):1144 self.assert_equal(meh(), 'http://localhost/meh')1145 self.assert_(flask._request_ctx_stack.top is None)11461147 def test_context_test(self):1148 app = flask.Flask(__name__)1149 self.assert_(not flask.request)1150 self.assert_(not flask.has_request_context())1151 ctx = app.test_request_context()1152 ctx.push()1153 try:1154 self.assert_(flask.request)1155 self.assert_(flask.has_request_context())1156 finally:1157 ctx.pop()11581159 def test_manual_context_binding(self):1160 app = flask.Flask(__name__)1161 @app.route('/')1162 def index():1163 return 'Hello %s!' % flask.request.args['name']11641165 ctx = app.test_request_context('/?name=World')1166 ctx.push()1167 self.assert_equal(index(), 'Hello World!')1168 ctx.pop()1169 try:1170 index()1171 except RuntimeError:1172 pass1173 else:1174 self.assert_(0, 'expected runtime error')117511761070class SubdomainTestCase(FlaskTestCase):10711072 def test_basic_support(self):1073 app = flask.Flask(__name__)
69 unmodified lines
11431144def suite():1145 suite = unittest.TestSuite()1146 suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1254 suite.addTest(unittest.makeSuite(ContextTestCase))1147 suite.addTest(unittest.makeSuite(SubdomainTestCase))1148 return suite
added:flask/testsuite/reqctx.py+187 added
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.reqctx4 ~~~~~~~~~~~~~~~~~~~~~~56 Tests the request context.78 :copyright: (c) 2012 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1314import flask15import unittest16try:17 from greenlet import greenlet18except ImportError:19 greenlet = None20from flask.testsuite import FlaskTestCase212223class RequestContextTestCase(FlaskTestCase):2425 def test_teardown_on_pop(self):26 buffer = []27 app = flask.Flask(__name__)28 @app.teardown_request29 def end_of_request(exception):30 buffer.append(exception)3132 ctx = app.test_request_context()33 ctx.push()34 self.assert_equal(buffer, [])35 ctx.pop()36 self.assert_equal(buffer, [None])3738 def test_proper_test_request_context(self):39 app = flask.Flask(__name__)40 app.config.update(41 SERVER_NAME='localhost.localdomain:5000'42 )4344 @app.route('/')45 def index():46 return None4748 @app.route('/', subdomain='foo')49 def sub():50 return None5152 with app.test_request_context('/'):53 self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')5455 with app.test_request_context('/'):56 self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')5758 try:59 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):60 pass61 except Exception, e:62 self.assert_(isinstance(e, ValueError))63 self.assert_equal(str(e), "the server name provided " +64 "('localhost.localdomain:5000') does not match the " + \65 "server name from the WSGI environment ('localhost')")6667 try:68 app.config.update(SERVER_NAME='localhost')69 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):70 pass71 except ValueError, e:72 raise ValueError(73 "No ValueError exception should have been raised \"%s\"" % e74 )7576 try:77 app.config.update(SERVER_NAME='localhost:80')78 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):79 pass80 except ValueError, e:81 raise ValueError(82 "No ValueError exception should have been raised \"%s\"" % e83 )8485 def test_context_binding(self):86 app = flask.Flask(__name__)87 @app.route('/')88 def index():89 return 'Hello %s!' % flask.request.args['name']90 @app.route('/meh')91 def meh():92 return flask.request.url9394 with app.test_request_context('/?name=World'):95 self.assert_equal(index(), 'Hello World!')96 with app.test_request_context('/meh'):97 self.assert_equal(meh(), 'http://localhost/meh')98 self.assert_(flask._request_ctx_stack.top is None)99100 def test_context_test(self):101 app = flask.Flask(__name__)102 self.assert_(not flask.request)103 self.assert_(not flask.has_request_context())104 ctx = app.test_request_context()105 ctx.push()106 try:107 self.assert_(flask.request)108 self.assert_(flask.has_request_context())109 finally:110 ctx.pop()111112 def test_manual_context_binding(self):113 app = flask.Flask(__name__)114 @app.route('/')115 def index():116 return 'Hello %s!' % flask.request.args['name']117118 ctx = app.test_request_context('/?name=World')119 ctx.push()120 self.assert_equal(index(), 'Hello World!')121 ctx.pop()122 try:123 index()124 except RuntimeError:125 pass126 else:127 self.assert_(0, 'expected runtime error')128129 def test_greenlet_context_copying(self):130 app = flask.Flask(__name__)131 greenlets = []132133 @app.route('/')134 def index():135 reqctx = flask._request_ctx_stack.top.copy()136 def g():137 self.assert_(not flask.request)138 self.assert_(not flask.current_app)139 with reqctx:140 self.assert_(flask.request)141 self.assert_equal(flask.current_app, app)142 self.assert_equal(flask.request.path, '/')143 self.assert_equal(flask.request.args['foo'], 'bar')144 self.assert_(not flask.request)145 return 42146 greenlets.append(greenlet(g))147 return 'Hello World!'148149 rv = app.test_client().get('/?foo=bar')150 self.assert_equal(rv.data, 'Hello World!')151152 result = greenlets[0].run()153 self.assert_equal(result, 42)154155 def test_greenlet_context_copying_api(self):156 app = flask.Flask(__name__)157 greenlets = []158159 @app.route('/')160 def index():161 reqctx = flask._request_ctx_stack.top.copy()162 @flask.copy_current_request_context163 def g():164 self.assert_(flask.request)165 self.assert_equal(flask.current_app, app)166 self.assert_equal(flask.request.path, '/')167 self.assert_equal(flask.request.args['foo'], 'bar')168 return 42169 greenlets.append(greenlet(g))170 return 'Hello World!'171172 rv = app.test_client().get('/?foo=bar')173 self.assert_equal(rv.data, 'Hello World!')174175 result = greenlets[0].run()176 self.assert_equal(result, 42)177178 # Disable test if we don't have greenlets available179 if greenlet is None:180 test_greenlet_context_copying = None181 test_greenlet_context_copying_api = None182183184def suite():185 suite = unittest.TestSuite()186 suite.addTest(unittest.makeSuite(RequestContextTestCase))187 return suite
modified:flask/__init__.py+1 added-1 removed
24 unmodified lines
25 stream_with_context26from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28from .ctx import has_request_context, has_app_context, \29 after_this_request29 after_this_request, copy_current_request_context30from .module import Module31from .blueprints import Blueprint32from .templating import render_template, render_template_string33
16 unmodified lines
modified:flask/app.py+6 added
1819 unmodified lines
18201821 def __call__(self, environ, start_response):1822 """Shortcut for :attr:`wsgi_app`."""1823 return self.wsgi_app(environ, start_response)18241825 def __repr__(self):1826 return '<%s %r>' % (1827 self.__class__.__name__,1828 self.name,1829 )
modified:flask/ctx.py+73 added-4 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112import sys13from functools import update_wrapper1415from werkzeug.exceptions import HTTPException1617from .globals import _request_ctx_stack, _app_ctx_stack
1 unmodified line
192021class _AppCtxGlobals(object):22 """A plain object."""22 pass2324 def __getitem__(self, name):25 try:26 return getattr(self, name)27 except AttributeError:28 return None2930 def __setitem__(self, name, value):31 setattr(self, name, value)3233 def __delitem__(self, name, value):34 delattr(self, name, value)3536 def __repr__(self):37 top = _app_ctx_stack.top38 if top is not None:39 return '<flask.g of %r>' % top.app.name40 return object.__repr__(self)414243def after_this_request(f):44 """Executes a function after this request. This is useful to modify45 response objects. The function is passed the response object and has46 to return the same or a new one.
17 unmodified lines
64 _request_ctx_stack.top._after_request_functions.append(f)65 return f666768def copy_current_request_context(f):69 """A helper function that decorates a function to retain the current70 request context. This is useful when working with greenlets. The moment71 the function is decorated a copy of the request context is created and72 then pushed when the function is called.7374 Example::7576 import gevent77 from flask import copy_current_request_context7879 @app.route('/')80 def index():81 @copy_current_request_context82 def do_some_work():83 # do some work here, it can access flask.request like you84 # would otherwise in the view function.85 ...86 gevent.spawn(do_some_work)87 return 'Regular response'8889 .. versionadded:: 0.1090 """91 top = _request_ctx_stack.top92 if top is None:93 raise RuntimeError('This decorator can only be used at local scopes '94 'when a request context is on the stack. For instance within '95 'view functions.')96 reqctx = top.copy()97 def wrapper(*args, **kwargs):98 with reqctx:99 return f(*args, **kwargs)100 return update_wrapper(wrapper, f)101102103def has_request_context():104 """If you have code that wants to test if a request context is there or105 not this function can be used. For instance, you may want to take advantage106 of request information if the request object is available, but fail
106 unmodified lines
213 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in214 that situation, otherwise your unittests will leak memory.215 """216164 def __init__(self, app, environ):217 def __init__(self, app, environ, request=None):218 self.app = app219 if request is None:166 self.request = app.request_class(environ)220 request = app.request_class(environ)221 self.request = request222 self.url_adapter = app.create_url_adapter(self.request)223 self.flashes = None224 self.session = None225
30 unmodified lines
256 _app_ctx_stack.top.g = value257 g = property(_get_g, _set_g)258 del _get_g, _set_g259260 def copy(self):261 """Creates a copy of this request context with the same request object.262 This can be used to move a request context to a different greenlet.263 Because the actual request object is the same this cannot be used to264 move a request context to a different thread unless access to the265 request object is locked.266267 .. versionadded:: 0.10268 """269 return self.__class__(self.app,270 environ=self.request.environ,271 request=self.request272 )273274 def match_request(self):275 """Can be overridden by a subclass to hook into the matching276 of the request.277 """
89 unmodified lines
367 return '<%s \'%s\' [%s] of %s>' % (368 self.__class__.__name__,369 self.request.url,370 self.request.method,302 self.app.name371 self.app.name,372 )
modified:CHANGES+2 added
50 unmodified lines
51 as intended with domain names.52- Changed logic for picking defaults for cookie values from sessions53 to work better with Google Chrome.54- Added `message_flashed` signal that simplifies flashing testing.55- Added support for copying of request contexts for better working with56 greenlets.5758Version 0.959-----------60
365 unmodified lines