Skip to content
Myr

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

12 files+290 added−60 removed

modified:docs/deploying/others.rst+1 added-1 removed
70 unmodified lines
71`HTTP_HOST`. Werkzeug ships a fixer that will solve some common setups,72but you might want to write your own WSGI middleware for specific setups.7374The most common setup invokes the host being set from `X-Forwarded-Host`75and the remote address from `X-Forward-For`::75and the remote address from `X-Forwarded-For`::7677 from werkzeug.contrib.fixers import ProxyFix78 app.wsgi_app = ProxyFix(app.wsgi_app)79
19 unmodified lines
added:docs/patterns/appdispatch.rst+154 added
1.. _app-dispatch:23Application Dispatching4=======================56Application dispatching is the process of combining multiple Flask7applications on the WSGI level. You can not only combine Flask8applications into something larger but any WSGI application. This would9even allow you to run a Django and a Flask application in the same10interpreter side by side if you want. The usefulness of this depends on11how the applications work internally.1213The fundamental difference from the :ref:`module approach14<larger-applications>` is that in this case you are running the same or15different Flask applications that are entirely isolated from each other.16They run different configurations and are dispatched on the WSGI level.1718Combining Applications19----------------------2021If you have entirely separated applications and you want them to work next22to each other in the same Python interpreter process you can take23advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea24here is that each Flask application is a valid WSGI application and they25are combined by the dispatcher middleware into a larger one that26dispatched based on prefix.2728For example you could have your main application run on `/` and your29backend interface on `/admin`::3031 from werkzeug.wsgi import DispatcherMiddleware32 from frontend_app import application as frontend33 from backend_app import application as backend3435 application = DispatcherMiddleware(frontend, {36 '/backend': backend37 })383940Dispatch by Subdomain41---------------------4243Sometimes you might want to use multiple instances of the same application44with different configurations. Assuming the application is created inside45a function and you can call that function to instanciate it, that is46really easy to implement. In order to develop your application to support47creating new instances in functions have a look at the48:ref:`app-factories` pattern.4950A very common example would be creating applications per subdomain. For51instance you configure your webserver to dispatch all requests for all52subdomains to your application and you then use the subdomain information53to create user-specific instances. Once you have your server set up to54listen on all subdomains you can use a very simple WSGI application to do55the dynamic application creation.5657The perfect level for abstraction in that regard is the WSGI layer. You58write your own WSGI application that looks at the request that comes and59and delegates it to your Flask application. If that application does not60exist yet, it is dynamically created and remembered::6162 from threading import Lock6364 class SubdomainDispatcher(object):6566 def __init__(self, domain, create_app):67 self.domain = domain68 self.create_app = create_app69 self.lock = Lock()70 self.instances = {}7172 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 app8283 def __call__(self, environ, start_response):84 app = self.get_application(environ['HTTP_HOST'])85 return app(environ, start_response)868788This dispatcher can then be used like this::8990 from myapplication import create_app, get_user_for_subdomain91 from werkzeug.exceptions import NotFound9293 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()102103 # otherwise create the application for the specific user104 return create_app(user)105106 application = SubdomainDispatcher('example.com', make_app)107108109Dispatch by Path110----------------111112Dispatching by a path on the URL is very similar. Instead of looking at113the `Host` header to figure out the subdomain one simply looks at the114request path up to the first slash::115116 from threading import Lock117 from werkzeug.wsgi import pop_path_info, peek_path_info118119 class PathDispatcher(object):120121 def __init__(self, default_app, create_app):122 self.default_app = default_app123 self.create_app = create_app124 self.lock = Lock()125 self.instances = {}126127 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 app135136 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)143144The big difference between this and the subdomain one is that this one145falls back to another application if the creator function returns `None`::146147 from myapplication import create_app, default_app, get_user_for_prefix148149 def make_app(prefix):150 user = get_user_for_prefix(prefix)151 if user is not None:152 return create_app(user)153154 application = PathDispatcher('example.com', default_app, make_app)
modified:docs/patterns/index.rst+1 added
16 unmodified lines
17 :maxdepth: 21819 packages20 appfactories21 appdispatch22 distribute23 fabric24 sqlite325 sqlalchemy
11 unmodified lines
modified:docs/tutorial/dbcon.rst+1 added-1 removed
22 unmodified lines
23 g.db.close()24 return response2526If you want to guarantee that the connection is always closed in debug mode, you27can close it in a function decorated with :meth:`~flask.Flask.teardown_request`:27can close it in a function decorated with :meth:`~flask.Flask.teardown_request`::2829 @app.before_request30 def before_request():31 g.db = connect_db()
25 unmodified lines
modified:docs/tutorial/setup.rst+8 added-1 removed
68 unmodified lines
69 if __name__ == '__main__':70 app.run()7172With that out of the way you should be able to start up the application73without problems. When you head over to the server you will get an 40473without problems. Do this with the following command::7475 python flaskr.py7677You will see a message telling you that server has started along with78the address at which you can access it.7980When you head over to the server in your browser you will get an 40481page not found error because we don't have any views yet. But we will82focus on that a little later. First we should get the database working.8384.. admonition:: Externally Visible Server
6 unmodified lines
modified:docs/api.rst+2 added
242 unmodified lines
243.. autofunction:: send_file244245.. autofunction:: send_from_directory246247.. autofunction:: safe_join248249.. autofunction:: escape250251.. autoclass:: Markup252 :members: escape, unescape, striptags
193 unmodified lines
modified:docs/extensiondev.rst+80 added-45 removed
135 unmodified lines
136Now this is where your extension code goes. But how exactly should such137an extension look like? What are the best practices? Continue reading138for some insight.139140140Initializing Extensions141-----------------------142143Many extensions will need some kind of initialization step. For example,
19 unmodified lines
163 some helper functions like `OAuth.remote_app` to create a reference to164 a remote application that uses OAuth.165166What to use depends on what you have in mind. For the SQLite 3 extension168we will need to use the class based approach because we have to use a169controller object that can be used to connect to the database.167we will use the class based approach because it will provide users with a168manager object that handles opening and closing database connections.169170The Extension Code171------------------172173Here's the contents of the `flaskext/sqlite3.py` for copy/paste::174175 from __future__ import absolute_import176 import sqlite3178 from flask import g177178 from flask import _request_ctx_stack179180 class SQLite3(object):181 181182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185186 self.app.before_request(self.before_request)185 self.app.after_request(self.after_request)186 self.app.before_request(self.before_request)187188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])190191 def before_request(self):192 ctx = _request_ctx_stack.top193 g.sqlite3_db = self.connect()193 ctx.sqlite3_db = self.connect()194195 def after_request(self, response):196 ctx = _request_ctx_stack.top196 g.sqlite3_db.close()197 ctx.sqlite3_db.close()198 return response199199So 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_db2042011. 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.2052. 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.2083. Then it implements a `connect` function that returns a new database209 connection and the two handlers.205So here's what these lines of code do:2062071. 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.2112. 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.2153. Next, we define a `connect` function that opens a database connection.2164. 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.2205. Finally, we add a `get_db` function that simplifies access to the context's221 database.222211So why did we decide on a class based approach here? Because using that223So why did we decide on a class based approach here? Because using our224extension looks something like this::225214 from flask import Flask, g226 from flask import Flask227 from flaskext.sqlite3 import SQLite3228229 app = Flask(__name__)230 app.config.from_pyfile('the-config.cfg')219 db = SQLite(app)231 manager = SQLite3(app)232 db = manager.get_db()233221Either way you can use the database from the views like this::234You can then use the database from views like this::235236 @app.route('/')237 def show_all():225 cur = g.sqlite3_db.cursor()238 cur = db.cursor()239 cur.execute(...)240228But how would you open a database connection from outside a view function?229This is where the `db` object now comes into play:241Opening a database connection from outside a view function is simple.242243>>> from yourapplication import db232>>> con = db.connect()233>>> cur = con.cursor()244>>> cur = db.cursor()245>>> cur.execute(...)246235If you don't need that, you can go with initialization functions.247Adding an `init_app` Function248-----------------------------249237Initialization Functions238------------------------250In practice, you'll almost always want to permit users to initialize your251extension and provide an app object after the fact. This can help avoid252circular import problems when a user is breaking their app into multiple files.253Our extension could add an `init_app` function as follows::254240Here's what the module would look like with initialization functions::255 class SQLite3(object):256242 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 = None263246 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)269250 @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'])272254 @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()276277 def after_request(self, response):278 ctx = _request_ctx_stack.top279 ctx.sqlite3_db.close()280 return response281282 def get_db(self):283 ctx = _request_ctx_stack.top284 if ctx is not None:285 return ctx.sqlite3_db286287The user could then initialize the extension in one file::288289 manager = SQLite3()290291and bind their app to the extension in another file::292293 manager.init_app(app)294295Learn from Others296-----------------297298This documentation only touches the bare minimum for extension
12 unmodified lines
311312The best Flask extensions are extensions that share common idioms for the313API. And this can only work if collaboration happens early.314279315Approved Extensions316-------------------317318Flask also has the concept of approved extensions. Approved extensions
44 unmodified lines
modified:flask/__init__.py+1 added-1 removed
17 unmodified lines
18from .app import Flask, Request, Response19from .config import Config20from .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_join23from .globals import current_app, g, request, session, _request_ctx_stack24from .ctx import has_request_context25from .module import Module26from .templating import render_template, render_template_string
9 unmodified lines
modified:flask/app.py+7 added-2 removed
711 unmodified lines
712 self.before_request_funcs.setdefault(None, []).append(f)713 return f714715 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 f722723 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 f729730 def context_processor(self, f):
287 unmodified lines
modified:flask/helpers.py+29 added-9 removed
164 unmodified lines
165 any ``'admin.index'`` `index` of the `admin` module166 ==================== ======================= =============================167168 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.171172 For more information, head over to the :ref:`Quickstart <url-building>`.173174 :param endpoint: the endpoint of the URL (name of the function)
146 unmodified lines
321 # 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 lines
388 rv.headers.pop('x-sendfile', None)389 return rv390391392def safe_join(directory, filename):393 """Safely join `directory` and `filename`.394395 Example usage::396397 @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...402403 :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)415416417def 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 lines
440 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 lines
modified:tests/flask_tests.py+5 added
45 unmodified lines
46@contextmanager47def catch_warnings():48 """Catch warnings in a with block in a list"""49 import warnings5051 # make sure deprecation warnings are active in tests52 warnings.simplefilter('default', category=DeprecationWarning)5354 filters = warnings.filters55 warnings.filters = filters[:]56 old_showwarning = warnings.showwarning57 log = []
583 unmodified lines
641 app = flask.Flask(__name__)642 app.config.update(643 SERVER_NAME='localhost.localdomain:5000'644 )645646 @app.route('/')647 def index():648 return None649
941 unmodified lines
modified:CHANGES+1 added
38 unmodified lines
39- 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`4445Version 0.6.146-------------47
159 unmodified lines