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
Provenance
- Commit
0973536- Tree
46e6bed- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
0faed95
7 files changed+272 added−114 removed
modified:docs/api.rst+2 added
278 unmodified lines279 This is a proxy. See :ref:`notes-on-proxies` for more information.280 281 .. autofunction:: has_request_context282 283+.. autofunction:: copy_current_request_context284+285 .. autofunction:: has_app_context286 287 .. autofunction:: url_for288 420 unmodified linesmodified:flask/testsuite/basic.py+1 added-109 removed
664 unmodified lines665 self.assert_('This was submitted: "index.txt"' in str(e))666 else:667 self.fail('Expected exception')668 669- 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)675-676- ctx = app.test_request_context()677- ctx.push()678- self.assert_equal(buffer, [])679- ctx.pop()680- self.assert_equal(buffer, [None])681-669 def test_response_creation(self):670 app = flask.Flask(__name__)671 @app.route('/unicode')672 def from_unicode():134 unmodified lines807 def test_request_locals(self):808 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')809 self.assertFalse(flask.g)810 824- def test_proper_test_request_context(self):825- app = flask.Flask(__name__)826- app.config.update(827- SERVER_NAME='localhost.localdomain:5000'828- )829-830- @app.route('/')831- def index():832- return None833-834- @app.route('/', subdomain='foo')835- def sub():836- return None837-838- with app.test_request_context('/'):839- self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')840-841- with app.test_request_context('/'):842- self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')843-844- 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')")852-853- 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- )861-862- 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- )870-811 def test_test_app_proper_environ(self):812 app = flask.Flask(__name__)813 app.config.update(814 SERVER_NAME='localhost.localdomain:5000'136 unmodified lines951 952 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)956 957 with app.test_request_context('/somepage'):958 url = flask.url_for('foo.bar.baz.view')959 expected = '/login'106 unmodified lines1066 self.assert_(flask._request_ctx_stack.top is None)1067 self.assert_(flask._app_ctx_stack.top is None)1068 1069 1130-class ContextTestCase(FlaskTestCase):1131-1132- 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.url1140-1141- 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)1146-1147- 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()1158-1159- 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']1164-1165- 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')1175-1176-1070 class SubdomainTestCase(FlaskTestCase):1071 1072 def test_basic_support(self):1073 app = flask.Flask(__name__)69 unmodified lines1143 1144 def 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 suiteadded:flask/testsuite/reqctx.py+187 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.testsuite.reqctx4+ ~~~~~~~~~~~~~~~~~~~~~~5+6+ Tests the request context.7+8+ :copyright: (c) 2012 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+from __future__ import with_statement13+14+import flask15+import unittest16+try:17+ from greenlet import greenlet18+except ImportError:19+ greenlet = None20+from flask.testsuite import FlaskTestCase21+22+23+class RequestContextTestCase(FlaskTestCase):24+25+ 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)31+32+ ctx = app.test_request_context()33+ ctx.push()34+ self.assert_equal(buffer, [])35+ ctx.pop()36+ self.assert_equal(buffer, [None])37+38+ def test_proper_test_request_context(self):39+ app = flask.Flask(__name__)40+ app.config.update(41+ SERVER_NAME='localhost.localdomain:5000'42+ )43+44+ @app.route('/')45+ def index():46+ return None47+48+ @app.route('/', subdomain='foo')49+ def sub():50+ return None51+52+ with app.test_request_context('/'):53+ self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')54+55+ with app.test_request_context('/'):56+ self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')57+58+ 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')")66+67+ 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+ )75+76+ 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+ )84+85+ 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.url93+94+ 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)99+100+ 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()111+112+ 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']117+118+ 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')128+129+ def test_greenlet_context_copying(self):130+ app = flask.Flask(__name__)131+ greenlets = []132+133+ @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!'148+149+ rv = app.test_client().get('/?foo=bar')150+ self.assert_equal(rv.data, 'Hello World!')151+152+ result = greenlets[0].run()153+ self.assert_equal(result, 42)154+155+ def test_greenlet_context_copying_api(self):156+ app = flask.Flask(__name__)157+ greenlets = []158+159+ @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!'171+172+ rv = app.test_client().get('/?foo=bar')173+ self.assert_equal(rv.data, 'Hello World!')174+175+ result = greenlets[0].run()176+ self.assert_equal(result, 42)177+178+ # Disable test if we don't have greenlets available179+ if greenlet is None:180+ test_greenlet_context_copying = None181+ test_greenlet_context_copying_api = None182+183+184+def suite():185+ suite = unittest.TestSuite()186+ suite.addTest(unittest.makeSuite(RequestContextTestCase))187+ return suitemodified:flask/__init__.py+1 added-1 removed
24 unmodified lines25 stream_with_context26 from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28 from .ctx import has_request_context, has_app_context, \29- after_this_request29+ after_this_request, copy_current_request_context30 from .module import Module31 from .blueprints import Blueprint32 from .templating import render_template, render_template_string33 16 unmodified linesmodified:flask/app.py+6 added
1819 unmodified lines1820 1821 def __call__(self, environ, start_response):1822 """Shortcut for :attr:`wsgi_app`."""1823 return self.wsgi_app(environ, start_response)1824+1825+ 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 lines9 :license: BSD, see LICENSE for more details.10 """11 12 import sys13+from functools import update_wrapper14 15 from werkzeug.exceptions import HTTPException16 17 from .globals import _request_ctx_stack, _app_ctx_stack1 unmodified line19 20 21 class _AppCtxGlobals(object):22 """A plain object."""22- pass23 24+ def __getitem__(self, name):25+ try:26+ return getattr(self, name)27+ except AttributeError:28+ return None29 30+ def __setitem__(self, name, value):31+ setattr(self, name, value)32+33+ def __delitem__(self, name, value):34+ delattr(self, name, value)35+36+ 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)41+42+43 def 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 lines64 _request_ctx_stack.top._after_request_functions.append(f)65 return f66 67 68+def 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.73+74+ Example::75+76+ import gevent77+ from flask import copy_current_request_context78+79+ @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'88+89+ .. 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)101+102+103 def 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 fail106 unmodified lines213 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in214 that situation, otherwise your unittests will leak memory.215 """216 164- 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 lines256 _app_ctx_stack.top.g = value257 g = property(_get_g, _set_g)258 del _get_g, _set_g259 260+ 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.266+267+ .. versionadded:: 0.10268+ """269+ return self.__class__(self.app,270+ environ=self.request.environ,271+ request=self.request272+ )273+274 def match_request(self):275 """Can be overridden by a subclass to hook into the matching276 of the request.277 """89 unmodified lines367 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 lines51 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.57 58 Version 0.959 -----------60 365 unmodified lines