Merge remote-tracking branch 'upstream/master' into issue_198
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Aaron Kavlie · committed by Aaron Kavlie · parents 1a7f579, 0171177 · Browse files · 12 files·+290 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+290 added−60 removed
- tests:+5 added−0 removed
- other:+285 added−60 removed
Provenance
- Commit
9d84a34- Tree
def69c5- Author
Aaron Kavlie <akavlie@gmail.com>- Committer
Aaron Kavlie <akavlie@gmail.com>- Parent 1
1a7f579- Parent 2
0171177
12 files changed+290 added−60 removed
modified:docs/deploying/others.rst+1 added-1 removed
70 unmodified lines71 `HTTP_HOST`. Werkzeug ships a fixer that will solve some common setups,72 but you might want to write your own WSGI middleware for specific setups.73 74 The most common setup invokes the host being set from `X-Forwarded-Host`75-and the remote address from `X-Forward-For`::75+and the remote address from `X-Forwarded-For`::76 77 from werkzeug.contrib.fixers import ProxyFix78 app.wsgi_app = ProxyFix(app.wsgi_app)79 19 unmodified linesadded:docs/patterns/appdispatch.rst+154 added
1+.. _app-dispatch:2+3+Application Dispatching4+=======================5+6+Application dispatching is the process of combining multiple Flask7+applications on the WSGI level. You can not only combine Flask8+applications into something larger but any WSGI application. This would9+even allow you to run a Django and a Flask application in the same10+interpreter side by side if you want. The usefulness of this depends on11+how the applications work internally.12+13+The fundamental difference from the :ref:`module approach14+<larger-applications>` is that in this case you are running the same or15+different Flask applications that are entirely isolated from each other.16+They run different configurations and are dispatched on the WSGI level.17+18+Combining Applications19+----------------------20+21+If you have entirely separated applications and you want them to work next22+to each other in the same Python interpreter process you can take23+advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea24+here is that each Flask application is a valid WSGI application and they25+are combined by the dispatcher middleware into a larger one that26+dispatched based on prefix.27+28+For example you could have your main application run on `/` and your29+backend interface on `/admin`::30+31+ from werkzeug.wsgi import DispatcherMiddleware32+ from frontend_app import application as frontend33+ from backend_app import application as backend34+35+ application = DispatcherMiddleware(frontend, {36+ '/backend': backend37+ })38+39+40+Dispatch by Subdomain41+---------------------42+43+Sometimes you might want to use multiple instances of the same application44+with different configurations. Assuming the application is created inside45+a function and you can call that function to instanciate it, that is46+really easy to implement. In order to develop your application to support47+creating new instances in functions have a look at the48+:ref:`app-factories` pattern.49+50+A very common example would be creating applications per subdomain. For51+instance you configure your webserver to dispatch all requests for all52+subdomains to your application and you then use the subdomain information53+to create user-specific instances. Once you have your server set up to54+listen on all subdomains you can use a very simple WSGI application to do55+the dynamic application creation.56+57+The perfect level for abstraction in that regard is the WSGI layer. You58+write your own WSGI application that looks at the request that comes and59+and delegates it to your Flask application. If that application does not60+exist yet, it is dynamically created and remembered::61+62+ from threading import Lock63+64+ class SubdomainDispatcher(object):65+66+ def __init__(self, domain, create_app):67+ self.domain = domain68+ self.create_app = create_app69+ self.lock = Lock()70+ self.instances = {}71+72+ def get_application(self, host):73+ host = host.split(':')[0]74+ assert host.endswith(self.domain), 'Configuration error'75+ subdomain = host[:-len(self.domain)].rstrip('.')76+ with self.lock:77+ app = self.instances.get(subdomain)78+ if app is None:79+ app = self.create_app(subdomain)80+ self.instances[subdomain] = app81+ return app82+83+ def __call__(self, environ, start_response):84+ app = self.get_application(environ['HTTP_HOST'])85+ return app(environ, start_response)86+87+88+This dispatcher can then be used like this::89+90+ from myapplication import create_app, get_user_for_subdomain91+ from werkzeug.exceptions import NotFound92+93+ def make_app(subdomain):94+ user = get_user_for_subdomain(subdomain)95+ if user is None:96+ # if there is no user for that subdomain we still have97+ # to return a WSGI application that handles that request.98+ # We can then just return the NotFound() exception as99+ # application which will render a default 404 page.100+ # You might also redirect the user to the main page then101+ return NotFound()102+103+ # otherwise create the application for the specific user104+ return create_app(user)105+106+ application = SubdomainDispatcher('example.com', make_app)107+108+109+Dispatch by Path110+----------------111+112+Dispatching by a path on the URL is very similar. Instead of looking at113+the `Host` header to figure out the subdomain one simply looks at the114+request path up to the first slash::115+116+ from threading import Lock117+ from werkzeug.wsgi import pop_path_info, peek_path_info118+119+ class PathDispatcher(object):120+121+ def __init__(self, default_app, create_app):122+ self.default_app = default_app123+ self.create_app = create_app124+ self.lock = Lock()125+ self.instances = {}126+127+ def get_application(self, prefix):128+ with self.lock:129+ app = self.instances.get(prefix)130+ if app is None:131+ app = self.create_app(prefix)132+ if app is not None:133+ self.instances[prefix] = app134+ return app135+136+ def __call__(self, environ, start_response):137+ app = self.get_application(peek_path_info(environ))138+ if app is not None:139+ pop_path_info(environ)140+ else:141+ app = self.default_app142+ return app(environ, start_response)143+144+The big difference between this and the subdomain one is that this one145+falls back to another application if the creator function returns `None`::146+147+ from myapplication import create_app, default_app, get_user_for_prefix148+149+ def make_app(prefix):150+ user = get_user_for_prefix(prefix)151+ if user is not None:152+ return create_app(user)153+154+ application = PathDispatcher('example.com', default_app, make_app)modified:docs/patterns/index.rst+1 added
16 unmodified lines17 :maxdepth: 218 19 packages20 appfactories21+ appdispatch22 distribute23 fabric24 sqlite325 sqlalchemy11 unmodified linesmodified:docs/tutorial/dbcon.rst+1 added-1 removed
22 unmodified lines23 g.db.close()24 return response25 26 If you want to guarantee that the connection is always closed in debug mode, you27-can close it in a function decorated with :meth:`~flask.Flask.teardown_request`:27+can close it in a function decorated with :meth:`~flask.Flask.teardown_request`::28 29 @app.before_request30 def before_request():31 g.db = connect_db()25 unmodified linesmodified:docs/tutorial/setup.rst+8 added-1 removed
68 unmodified lines69 if __name__ == '__main__':70 app.run()71 72 With that out of the way you should be able to start up the application73-without problems. When you head over to the server you will get an 40473+without problems. Do this with the following command::74+75+ python flaskr.py76+77+You will see a message telling you that server has started along with78+the address at which you can access it.79+80+When you head over to the server in your browser you will get an 40481 page not found error because we don't have any views yet. But we will82 focus on that a little later. First we should get the database working.83 84 .. admonition:: Externally Visible Server6 unmodified linesmodified:docs/api.rst+2 added
242 unmodified lines243 .. autofunction:: send_file244 245 .. autofunction:: send_from_directory246 247+.. autofunction:: safe_join248+249 .. autofunction:: escape250 251 .. autoclass:: Markup252 :members: escape, unescape, striptags193 unmodified linesmodified:docs/extensiondev.rst+80 added-45 removed
135 unmodified lines136 Now this is where your extension code goes. But how exactly should such137 an extension look like? What are the best practices? Continue reading138 for some insight.139 140-140 Initializing Extensions141 -----------------------142 143 Many extensions will need some kind of initialization step. For example,19 unmodified lines163 some helper functions like `OAuth.remote_app` to create a reference to164 a remote application that uses OAuth.165 166 What to use depends on what you have in mind. For the SQLite 3 extension168-we will need to use the class based approach because we have to use a169-controller object that can be used to connect to the database.167+we will use the class based approach because it will provide users with a168+manager object that handles opening and closing database connections.169 170 The Extension Code171 ------------------172 173 Here's the contents of the `flaskext/sqlite3.py` for copy/paste::174 175 from __future__ import absolute_import176 import sqlite3178- from flask import g177 178+ from flask import _request_ctx_stack179+180 class SQLite3(object):181- 181+182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185-186- self.app.before_request(self.before_request)185 self.app.after_request(self.after_request)186+ self.app.before_request(self.before_request)187 188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])190 191 def before_request(self):192+ ctx = _request_ctx_stack.top193- g.sqlite3_db = self.connect()193+ ctx.sqlite3_db = self.connect()194 195 def after_request(self, response):196+ ctx = _request_ctx_stack.top196- g.sqlite3_db.close()197+ ctx.sqlite3_db.close()198 return response199 199-So here's what the lines of code do:200+ def get_db(self):201+ ctx = _request_ctx_stack.top202+ if ctx is not None:203+ return ctx.sqlite3_db204 201-1. the ``__future__`` import is necessary to activate absolute imports.202- This is needed because otherwise we could not call our module203- `sqlite3.py` and import the top-level `sqlite3` module which actually204- implements the connection to SQLite.205-2. We create a class for our extension that sets a default configuration206- for the SQLite 3 database if it's not there (:meth:`dict.setdefault`)207- and connects two functions as before and after request handlers.208-3. Then it implements a `connect` function that returns a new database209- connection and the two handlers.205+So here's what these lines of code do:206 207+1. The ``__future__`` import is necessary to activate absolute imports.208+ Otherwise we could not call our module `sqlite3.py` and import the209+ top-level `sqlite3` module which actually implements the connection to210+ SQLite.211+2. We create a class for our extension that requires a supplied `app` object,212+ sets a configuration for the database if it's not there213+ (:meth:`dict.setdefault`), and attaches `before_request` and214+ `after_request` handlers.215+3. Next, we define a `connect` function that opens a database connection.216+4. Then we set up the request handlers we bound to the app above. Note here217+ that we're attaching our database connection to the top request context via218+ `_request_ctx_stack.top`. Extensions should use the top context and not the219+ `g` object to store things like database connections.220+5. Finally, we add a `get_db` function that simplifies access to the context's221+ database.222+211-So why did we decide on a class based approach here? Because using that223+So why did we decide on a class based approach here? Because using our224 extension looks something like this::225 214- from flask import Flask, g226+ from flask import Flask227 from flaskext.sqlite3 import SQLite3228 229 app = Flask(__name__)230 app.config.from_pyfile('the-config.cfg')219- db = SQLite(app)231+ manager = SQLite3(app)232+ db = manager.get_db()233 221-Either way you can use the database from the views like this::234+You can then use the database from views like this::235 236 @app.route('/')237 def show_all():225- cur = g.sqlite3_db.cursor()238+ cur = db.cursor()239 cur.execute(...)240 228-But how would you open a database connection from outside a view function?229-This is where the `db` object now comes into play:241+Opening a database connection from outside a view function is simple.242 243 >>> from yourapplication import db232->>> con = db.connect()233->>> cur = con.cursor()244+>>> cur = db.cursor()245+>>> cur.execute(...)246 235-If you don't need that, you can go with initialization functions.247+Adding an `init_app` Function248+-----------------------------249 237-Initialization Functions238-------------------------250+In practice, you'll almost always want to permit users to initialize your251+extension and provide an app object after the fact. This can help avoid252+circular import problems when a user is breaking their app into multiple files.253+Our extension could add an `init_app` function as follows::254 240-Here's what the module would look like with initialization functions::255+ class SQLite3(object):256 242- from __future__ import absolute_import243- import sqlite3244- from flask import g257+ def __init__(self, app=None):258+ if app is not None:259+ self.app = app260+ self.init_app(self.app)261+ else:262+ self.app = None263 246- def init_sqlite3(app):247- app = app248- app.config.setdefault('SQLITE3_DATABASE', ':memory:')264+ def init_app(self, app):265+ self.app = app266+ self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')267+ self.app.after_request(self.after_request)268+ self.app.before_request(self.before_request)269 250- @app.before_request251- def before_request():252- g.sqlite3_db = sqlite3.connect(self.app.config['SQLITE3_DATABASE'])270+ def connect(self):271+ return sqlite3.connect(app.config['SQLITE3_DATABASE'])272 254- @app.after_request255- def after_request(response):256- g.sqlite3_db.close()273+ def before_request(self):274+ ctx = _request_ctx_stack.top275+ ctx.sqlite3_db = self.connect()276+277+ def after_request(self, response):278+ ctx = _request_ctx_stack.top279+ ctx.sqlite3_db.close()280 return response281 282+ def get_db(self):283+ ctx = _request_ctx_stack.top284+ if ctx is not None:285+ return ctx.sqlite3_db286+287+The user could then initialize the extension in one file::288+289+ manager = SQLite3()290+291+and bind their app to the extension in another file::292+293+ manager.init_app(app)294+295 Learn from Others296 -----------------297 298 This documentation only touches the bare minimum for extension12 unmodified lines311 312 The best Flask extensions are extensions that share common idioms for the313 API. And this can only work if collaboration happens early.314 279-315 Approved Extensions316 -------------------317 318 Flask also has the concept of approved extensions. Approved extensions44 unmodified linesmodified:flask/__init__.py+1 added-1 removed
17 unmodified lines18 from .app import Flask, Request, Response19 from .config import Config20 from .helpers import url_for, jsonify, json_available, flash, \21 send_file, send_from_directory, get_flashed_messages, \22- get_template_attribute, make_response22+ get_template_attribute, make_response, safe_join23 from .globals import current_app, g, request, session, _request_ctx_stack24 from .ctx import has_request_context25 from .module import Module26 from .templating import render_template, render_template_string9 unmodified linesmodified:flask/app.py+7 added-2 removed
711 unmodified lines712 self.before_request_funcs.setdefault(None, []).append(f)713 return f714 715 def after_request(self, f):716- """Register a function to be run after each request."""716+ """Register a function to be run after each request. Your function717+ must take one parameter, a :attr:`response_class` object and return718+ a new response object or the same (see :meth:`process_response`).719+ """720 self.after_request_funcs.setdefault(None, []).append(f)721 return f722 723 def teardown_request(self, f):721- """Register a function to be run at the end of each request, regardless of whether there was an exception or not."""724+ """Register a function to be run at the end of each request,725+ regardless of whether there was an exception or not.726+ """727 self.teardown_request_funcs.setdefault(None, []).append(f)728 return f729 730 def context_processor(self, f):287 unmodified linesmodified:flask/helpers.py+29 added-9 removed
164 unmodified lines165 any ``'admin.index'`` `index` of the `admin` module166 ==================== ======================= =============================167 168 Variable arguments that are unknown to the target endpoint are appended169- to the generated URL as query arguments.169+ to the generated URL as query arguments. If the value of a query argument170+ is `None`, the whole pair is skipped.171 172 For more information, head over to the :ref:`Quickstart <url-building>`.173 174 :param endpoint: the endpoint of the URL (name of the function)146 unmodified lines321 # removed in Flask 1.0322 if not attachment_filename and not mimetype \323 and isinstance(filename, basestring):324 warn(DeprecationWarning('The filename support for file objects '324- 'passed to send_file is not deprecated. Pass an '325+ 'passed to send_file is now deprecated. Pass an '326 'attach_filename if you want mimetypes to be guessed.'),327 stacklevel=2)328 if add_etags:329 warn(DeprecationWarning('In future flask releases etags will no '58 unmodified lines388 rv.headers.pop('x-sendfile', None)389 return rv390 391 392+def safe_join(directory, filename):393+ """Safely join `directory` and `filename`.394+395+ Example usage::396+397+ @app.route('/wiki/<path:filename>')398+ def wiki_page(filename):399+ filename = safe_join(app.config['WIKI_FOLDER'], filename)400+ with open(filename, 'rb') as fd:401+ content = fd.read() # Read and process the file content...402+403+ :param directory: the base directory.404+ :param filename: the untrusted filename relative to that directory.405+ :raises: :class:`~werkzeug.exceptions.NotFound` if the retsulting path406+ would fall out of `directory`.407+ """408+ filename = posixpath.normpath(filename)409+ for sep in _os_alt_seps:410+ if sep in filename:411+ raise NotFound()412+ if os.path.isabs(filename) or filename.startswith('../'):413+ raise NotFound()414+ return os.path.join(directory, filename)415+416+417 def send_from_directory(directory, filename, **options):418 """Send a file from a given directory with :func:`send_file`. This419 is a secure way to quickly expose static files from an upload folder420 or something similar.19 unmodified lines440 download.441 :param options: optional keyword arguments that are directly442 forwarded to :func:`send_file`.443 """418- filename = posixpath.normpath(filename)419- for sep in _os_alt_seps:420- if sep in filename:421- raise NotFound()422- if os.path.isabs(filename) or filename.startswith('../'):423- raise NotFound()424- filename = os.path.join(directory, filename)444+ filename = safe_join(directory, filename)445 if not os.path.isfile(filename):446 raise NotFound()447 return send_file(filename, conditional=True, **options)448 68 unmodified linesmodified:tests/flask_tests.py+5 added
45 unmodified lines46 @contextmanager47 def catch_warnings():48 """Catch warnings in a with block in a list"""49 import warnings50+51+ # make sure deprecation warnings are active in tests52+ warnings.simplefilter('default', category=DeprecationWarning)53+54 filters = warnings.filters55 warnings.filters = filters[:]56 old_showwarning = warnings.showwarning57 log = []583 unmodified lines641 app = flask.Flask(__name__)642 app.config.update(643 SERVER_NAME='localhost.localdomain:5000'644 )645+646 @app.route('/')647 def index():648 return None649 941 unmodified linesmodified:CHANGES+1 added
38 unmodified lines39 - Implemented a silent flag for `config.from_pyfile`.40 - Added `teardown_request` decorator, for functions that should run at the end41 of a request regardless of whether an exception occurred.42 - Implemented :func:`flask.has_request_context`43+- Added :func:`safe_join`44 45 Version 0.6.146 -------------47 159 unmodified lines