Merge branch '1.0.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents d68abe9, ded0f68 · Browse files · 18 files·+76 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
18 files+76 added−60 removed
- other:+76 added−60 removed
Provenance
- Commit
2236ba9- Tree
7fc82b3- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
d68abe9- Parent 2
ded0f68
18 files changed+76 added−60 removed
modified:docs/deploying/wsgi-standalone.rst+9 added-3 removed
21 unmodified lines22 4``) binding to localhost port 4000 (``-b 127.0.0.1:4000``)::23 24 $ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app25 26+The ``gunicorn`` command expects the names of your application module or27+package and the application instance within the module. If you use the28+application factory pattern, you can pass a call to that::29+30+ $ gunicorn "myproject:create_app()"31+32 .. _Gunicorn: https://gunicorn.org/33 .. _eventlet: https://eventlet.net/28-.. _greenlet: https://greenlet.readthedocs.io/en/latest/34 35+36 uWSGI37 --------38 39 `uWSGI`_ is a fast application server written in C. It is very configurable88 unmodified lines128 If your httpd is not providing these headers, the most common setup invokes the129 host being set from ``X-Forwarded-Host`` and the remote address from130 ``X-Forwarded-For``::131 126- from werkzeug.contrib.fixers import ProxyFix127- app.wsgi_app = ProxyFix(app.wsgi_app)132+ from werkzeug.middleware.proxy_fix import ProxyFix133+ app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)134 135 .. admonition:: Trusting Headers136 137 Please keep in mind that it is a security issue to use such a middleware in18 unmodified linesmodified:docs/patterns/methodoverrides.rst+5 added-6 removed
1 Adding HTTP Method Overrides2 ============================3 4 Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP5-methods (such as PATCH). In that case it's possible to “proxy” HTTP5+methods (such as PATCH). In that case it's possible to "proxy" HTTP6 methods through another HTTP method in total violation of the protocol.7 8 The way this works is by letting the client do an HTTP POST request and9-set the ``X-HTTP-Method-Override`` header and set the value to the10-intended HTTP method (such as ``PATCH``).9+set the ``X-HTTP-Method-Override`` header. Then the method is replaced10+with the header value before being passed to Flask.11 12-This can easily be accomplished with an HTTP middleware::12+This can be accomplished with an HTTP middleware::13 14 class HTTPMethodOverrideMiddleware(object):15 allowed_methods = frozenset([16 'GET',11 unmodified lines28 29 def __call__(self, environ, start_response):30 method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()31 if method in self.allowed_methods:32- method = method.encode('ascii', 'replace')32 environ['REQUEST_METHOD'] = method33 if method in self.bodyless_methods:34 environ['CONTENT_LENGTH'] = '0'35 return self.app(environ, start_response)36 38-To use this with Flask this is all that is necessary::37+To use this with Flask, wrap the app object with the middleware::38 39 from flask import Flask40 41 app = Flask(__name__)1 unmodified linemodified:docs/api.rst+1 added-1 removed
724 unmodified lines725 requests, make sure the default route only handles ``GET``, as redirects726 can't preserve form data. ::727 728 @app.route('/region/', defaults={'id': 1})729- @app.route('/region/<id>', methods=['GET', 'POST'])729+ @app.route('/region/<int:id>', methods=['GET', 'POST'])730 def region(id):731 pass732 733 Here are the parameters that :meth:`~flask.Flask.route` and100 unmodified linesmodified:docs/appcontext.rst+1 added-1 removed
47 unmodified lines48 Typically, an application context will have the same lifetime as a49 request.50 51 See :doc:`/reqcontext` for more information about how the contexts work52-and the full lifecycle of a request.52+and the full life cycle of a request.53 54 55 Manually Push a Context56 -----------------------103 unmodified linesmodified:docs/becomingbig.rst+1 added-1 removed
95 unmodified lines96 ---------------------------97 98 The Flask developers keep the framework accessible to users with codebases big99 and small. If you find an obstacle in your way, caused by Flask, don't hesitate100-to contact the developers on the mailinglist or IRC channel. The best way for100+to contact the developers on the mailing list or IRC channel. The best way for101 the Flask and Flask extension developers to improve the tools for larger102 applications is getting feedback from users.modified:docs/blueprints.rst+8 added-9 removed
244 unmodified lines245 246 Error Handlers247 --------------248 249-Blueprints support the errorhandler decorator just like the :class:`Flask`249+Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`250 application object, so it is easy to make Blueprint-specific custom error251 pages.252 253 Here is an example for a "404 Page Not Found" exception::3 unmodified lines257 return render_template('pages/404.html')258 259 Most errorhandlers will simply work as expected; however, there is a caveat260 concerning handlers for 404 and 405 exceptions. These errorhandlers are only261-invoked from an appropriate ``raise`` statement or a call to ``abort``262-in another of the blueprint's view functions; they are not invoked by,263-e.g., an invalid URL access. This is because the blueprint does not264-"own" a certain URL space, so the application instance has no way of265-knowing which blueprint errorhandler it should run if given an invalid URL.266-If you would like to execute different handling strategies for these errors267-based on URL prefixes, they may be defined at the application level using268-the ``request`` proxy object::261+invoked from an appropriate ``raise`` statement or a call to ``abort`` in another262+of the blueprint's view functions; they are not invoked by, e.g., an invalid URL263+access. This is because the blueprint does not "own" a certain URL space, so264+the application instance has no way of knowing which blueprint error handler it265+should run if given an invalid URL. If you would like to execute different266+handling strategies for these errors based on URL prefixes, they may be defined267+at the application level using the ``request`` proxy object::268 269 @app.errorhandler(404)270 @app.errorhandler(405)271 def _handle_api_error(ex):6 unmodified linesmodified:docs/cli.rst+3 added-3 removed
66 unmodified lines67 ``FLASK_APP="hello:create_app('dev')"``68 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``69 as the argument.70 71-If ``FLASK_APP`` is not set, the command will look for a file called72-:file:`wsgi.py` or :file:`app.py` and try to detect an application instance or73-factory.71+If ``FLASK_APP`` is not set, the command will try to import "app" or72+"wsgi" (as a ".py" file, or package) and try to detect an application73+instance or factory.74 75 Within the given import, the command looks for an application instance named76 ``app`` or ``application``, then any application instance. If no instance is77 found, the command looks for a factory function named ``create_app`` or391 unmodified linesmodified:docs/config.rst+12 added-14 removed
7 unmodified lines8 toggling the debug mode, setting the secret key, and other such9 environment-specific things.10 11 The way Flask is designed usually requires the configuration to be12-available when the application starts up. You can hardcode the12+available when the application starts up. You can hard code the13 configuration in the code, which for many small applications is not14 actually that bad, but there are better ways.15 16 Independent of how you load your config, there is a config object419 unmodified lines436 methods on the config object as well to load from individual files. For a437 complete reference, read the :class:`~flask.Config` object's438 documentation.439 440+441 Configuring from Environment Variables442 --------------------------------------443 444 In addition to pointing to configuration files using environment variables, you3 unmodified lines448 Environment variables can be set on Linux or OS X with the export command in449 the shell before starting the server::450 451 $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'451- $ export DEBUG=False452+ $ export MAIL_ENABLED=false453 $ python run-app.py454 * Running on http://127.0.0.1:5000/454- * Restarting with reloader...455 456-On Windows systems use the `set` builtin instead::456+On Windows systems use the ``set`` builtin instead::457 458 > set SECRET_KEY='5f352379324c22463451387a0aec5d2f'459- > set DEBUG=False459 460 While this approach is straightforward to use, it is important to remember that461 environment variables are strings -- they are not automatically deserialized462 into Python types.463 464 Here is an example of a configuration file that uses environment variables::465 467- # Example configuration466 import os467 470- ENVIRONMENT_DEBUG = os.environ.get("DEBUG", default=False)471- if ENVIRONMENT_DEBUG.lower() in ("f", "false"):472- ENVIRONMENT_DEBUG = False468+ _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")469+ MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}470 474- DEBUG = ENVIRONMENT_DEBUG475- SECRET_KEY = os.environ.get("SECRET_KEY", default=None)471+ SECRET_KEY = os.environ.get("SECRET_KEY")472+473 if not SECRET_KEY:477- raise ValueError("No secret key set for Flask application")474+ raise ValueError("No SECRET_KEY set for Flask application")475 476 477 Notice that any value besides an empty string will be interpreted as a boolean478 ``True`` value in Python, which requires care if an environment explicitly sets3 unmodified lines482 ability to access the configuration when starting up. There are other methods483 on the config object as well to load from individual files. For a complete484 reference, read the :class:`~flask.Config` class documentation.485 486+487 Configuration Best Practices488 ----------------------------489 490 The downside with the approach mentioned earlier is that it makes testing2 unmodified lines493 that experience:494 495 1. Create your application in a function and register blueprints on it.496 That way you can create multiple instances of your application with499- different configurations attached which makes unittesting a lot497+ different configurations attached which makes unit testing a lot498 easier. You can use this to pass in configuration as needed.499 500 2. Do not write code that needs the configuration at import time. If you501 limit yourself to request-only accesses to the configuration you can24 unmodified lines526 the config file by adding ``from yourapplication.default_settings527 import *`` to the top of the file and then overriding the changes by hand.528 You could also inspect an environment variable like529 ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc532-and import different hardcoded files based on that.530+and import different hard-coded files based on that.531 532 An interesting pattern is also to use classes and inheritance for533 configuration::534 160 unmodified linesmodified:docs/design.rst+2 added-2 removed
39 unmodified lines40 the time. There are ways to fake multiple applications with a single41 application object, like maintaining a stack of applications, but this42 causes some problems I won't outline here in detail. Now the question is:43 when does a microframework need more than one application at the same44-time? A good example for this is unittesting. When you want to test44+time? A good example for this is unit testing. When you want to test45 something it can be very helpful to create a minimal application to test46 specific behavior. When the application object is deleted everything it47 allocated will be freed again.48 26 unmodified lines75 there are better ways to do that so that you do not lose the reference76 to the application object :meth:`~flask.Flask.wsgi_app`).77 78 Furthermore this design makes it possible to use a factory function to79-create the application which is very helpful for unittesting and similar79+create the application which is very helpful for unit testing and similar80 things (:ref:`app-factories`).81 82 The Routing System83 ------------------108 unmodified linesmodified:docs/extensiondev.rst+1 added-1 removed
285 unmodified lines286 also avoids having multiple developers working in isolation on pretty much the287 same problem.288 289 Remember: good API design is hard, so introduce your project on the290-mailinglist, and let other developers give you a helping hand with290+mailing list, and let other developers give you a helping hand with291 designing the API.292 293 The best Flask extensions are extensions that share common idioms for the294 API. And this can only work if collaboration happens early.51 unmodified linesmodified:docs/extensions.rst+1 added-1 removed
4 unmodified lines5 6 Extensions are extra packages that add functionality to a Flask7 application. For example, an extension might add support for sending8 email or connecting to a database. Some extensions add entire new9-frameworks to help build certain types of applications, like a ReST API.9+frameworks to help build certain types of applications, like a REST API.10 11 12 Finding Extensions13 ------------------40 unmodified linesmodified:docs/quickstart.rst+8 added-8 removed
201 unmodified lines202 203 @app.route('/user/<username>')204 def show_user_profile(username):205 # show the user profile for that user206- return 'User %s' % username206+ return 'User %s' % escape(username)207 208 @app.route('/post/<int:post_id>')209 def show_post(post_id):210 # show the post with the given id, the id is an integer1 unmodified line212 213 @app.route('/path/<path:subpath>')214 def show_subpath(subpath):215 # show the subpath after /path/216- return 'Subpath %s' % subpath216+ return 'Subpath %s' % escape(subpath)217 218 Converter types:219 220 ========== ==========================================59 unmodified lines280 Python shell. See :ref:`context-locals`.281 282 .. code-block:: python283 284- from flask import Flask, url_for284+ from flask import Flask, escape, url_for285 286 app = Flask(__name__)287 288 @app.route('/')5 unmodified lines294 return 'login'295 296 @app.route('/user/<username>')297 def profile(username):298- return '{}\'s profile'.format(username)298+ return '{}\'s profile'.format(escape(username))299 300 with app.test_request_context():301 print(url_for('index'))302 print(url_for('login'))386 unmodified lines689 1. If a response object of the correct type is returned it's directly690 returned from the view.691 2. If it's a string, a response object is created with that data and the692 default parameters.693-3. If a tuple is returned the items in the tuple can provide extra694- information. Such tuples have to be in the form ``(response, status,695- headers)`` or ``(response, headers)`` where at least one item has696- to be in the tuple. The ``status`` value will override the status code693+3. If a tuple is returned the items in the tuple can provide extra information.694+ Such tuples have to be in the form ``(response, status, headers)``,695+ ``(response, headers)`` or ``(response, status)`` where at least one item696+ has to be in the tuple. The ``status`` value will override the status code697 and ``headers`` can be a list or dictionary of additional header values.698 4. If none of that works, Flask will assume the return value is a699 valid WSGI application and convert that into a response object.700 158 unmodified linesmodified:docs/shell.rst+1 added-1 removed
18 unmodified lines19 can you do?20 21 This is where some helper functions come in handy. Keep in mind however22 that these functions are not only there for interactive shell usage, but23-also for unittesting and other situations that require a faked request23+also for unit testing and other situations that require a faked request24 context.25 26 Generally it's recommended that you read the :ref:`request-context`27 chapter of the documentation first.76 unmodified linesmodified:docs/unicode.rst+2 added-2 removed
41 unmodified lines42 43 So the rule of thumb: if you are not dealing with binary data, work with44 Unicode. What does working with Unicode in Python 2.x mean?45 46-- as long as you are using ASCII charpoints only (basically numbers,47- some special characters of latin letters without umlauts or anything46+- as long as you are using ASCII code points only (basically numbers,47+ some special characters of Latin letters without umlauts or anything48 fancy) you can use regular string literals (``'Hello World'``).49 - if you need anything else than ASCII in a string you have to mark50 this string as Unicode string by prefixing it with a lowercase `u`.51 (like ``u'Hänsel und Gretel'``)56 unmodified linesmodified:flask/ctx.py+1 added-1 removed
173 unmodified lines174 remote_addr = request.remote_addr175 self.remote_addr = remote_addr176 177 Alternatively you can also just test any of the context bound objects178- (such as :class:`request` or :class:`g` for truthness)::178+ (such as :class:`request` or :class:`g`) for truthness::179 180 class User(db.Model):181 182 def __init__(self, username, remote_addr=None):291 unmodified linesmodified:flask/helpers.py+1 added-1 removed
276 unmodified lines277 :param endpoint: the endpoint of the URL (name of the function)278 :param values: the variable arguments of the URL rule279 :param _external: if set to ``True``, an absolute URL is generated. Server280 address can be changed via ``SERVER_NAME`` configuration variable which281- defaults to `localhost`.281+ falls back to the `Host` header, then to the IP and port of the request.282 :param _scheme: a string specifying the desired URL scheme. The `_external`283 parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default284 behavior uses the same scheme as the current request, or285 ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no816 unmodified linesmodified:CONTRIBUTING.rst+18 added-5 removed
7 unmodified lines8 9 Please, don't use the issue tracker for this. Use one of the following10 resources for questions about your own code:11 12-* The IRC channel ``#pocoo`` on FreeNode.13-* The IRC channel ``#python`` on FreeNode for more general questions.12+* The ``#get-help`` channel on our Discord chat: https://discord.gg/t6rrQZH13+ * The IRC channel ``#pocoo`` on FreeNode is linked to Discord, but14+ Discord is preferred.15 * The mailing list flask@python.org for long term discussion or larger issues.16 * Ask on `Stack Overflow`_. Search with Google first using:17 ``site:stackoverflow.com flask {search term, exception message, etc.}``18 62 unmodified lines81 82 Start coding83 ~~~~~~~~~~~~84 84-- Create a branch to identify the issue you would like to work on (e.g.85- ``2287-dry-test-suite``)85+- Create a branch to identify the issue you would like to work on. If86+ you're submitting a bug or documentation fix, branch off of the87+ latest ".x" branch::88+89+ git checkout -b your-branch-name origin/1.0.x90+91+ If you're submitting a feature addition or change, branch off of the92+ "master" branch::93+94+ git checkout -b your-branch-name origin/master95+96 - Using your favorite editor, make your changes, `committing as you go`_.97 - Try to follow `PEP8`_, but you may ignore the line length limit if following98 it would make the code uglier.99 - Include tests that cover any code changes you make. Make sure the test fails100 without your patch. `Run the tests. <contributing-testsuite_>`_.91-- Push your commits to GitHub and `create a pull request`_.101+- Push your commits to GitHub and `create a pull request`_ by using::102+103+ git push --set-upstream origin your-branch-name104+105 - Celebrate 🎉106 107 .. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes108 .. _PEP8: https://pep8.org/85 unmodified linesmodified:README.rst+1 added
73 unmodified lines74 * Issue tracker: https://github.com/pallets/flask/issues75 * Test status: https://dev.azure.com/pallets/pallets/_build?definitionId=276 77 * Test coverage: https://codecov.io/gh/pallets/flask78+* Official chat: https://discord.gg/t6rrQZH79 80 .. _WSGI: https://wsgi.readthedocs.io81 .. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/82 .. _Jinja: https://www.palletsprojects.com/p/jinja/1 unmodified line