Skip to content
Myr

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

18 files+76 added−60 removed

modified:docs/deploying/wsgi-standalone.rst+9 added-3 removed
21 unmodified lines
224``) binding to localhost port 4000 (``-b 127.0.0.1:4000``)::2324 $ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app2526The ``gunicorn`` command expects the names of your application module or27package and the application instance within the module. If you use the28application factory pattern, you can pass a call to that::2930 $ gunicorn "myproject:create_app()"3132.. _Gunicorn: https://gunicorn.org/33.. _eventlet: https://eventlet.net/28.. _greenlet: https://greenlet.readthedocs.io/en/latest/343536uWSGI37--------3839`uWSGI`_ is a fast application server written in C. It is very configurable
88 unmodified lines
128If your httpd is not providing these headers, the most common setup invokes the129host being set from ``X-Forwarded-Host`` and the remote address from130``X-Forwarded-For``::131126 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)134135.. admonition:: Trusting Headers136137 Please keep in mind that it is a security issue to use such a middleware in
18 unmodified lines
modified:docs/patterns/methodoverrides.rst+5 added-6 removed
1Adding HTTP Method Overrides2============================34Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP5methods (such as PATCH). In that case it's possible to “proxy” HTTP5methods (such as PATCH). In that case it's possible to "proxy" HTTP6methods through another HTTP method in total violation of the protocol.78The way this works is by letting the client do an HTTP POST request and9set the ``X-HTTP-Method-Override`` header and set the value to the10intended HTTP method (such as ``PATCH``).9set the ``X-HTTP-Method-Override`` header. Then the method is replaced10with the header value before being passed to Flask.1112This can easily be accomplished with an HTTP middleware::12This can be accomplished with an HTTP middleware::1314 class HTTPMethodOverrideMiddleware(object):15 allowed_methods = frozenset([16 'GET',
11 unmodified lines
2829 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)3638To use this with Flask this is all that is necessary::37To use this with Flask, wrap the app object with the middleware::3839 from flask import Flask4041 app = Flask(__name__)
1 unmodified line
modified:docs/api.rst+1 added-1 removed
724 unmodified lines
725requests, make sure the default route only handles ``GET``, as redirects726can't preserve form data. ::727728 @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 pass732733Here are the parameters that :meth:`~flask.Flask.route` and
100 unmodified lines
modified:docs/appcontext.rst+1 added-1 removed
47 unmodified lines
48Typically, an application context will have the same lifetime as a49request.5051See :doc:`/reqcontext` for more information about how the contexts work52and the full lifecycle of a request.52and the full life cycle of a request.535455Manually Push a Context56-----------------------
103 unmodified lines
modified:docs/becomingbig.rst+1 added-1 removed
95 unmodified lines
96---------------------------9798The Flask developers keep the framework accessible to users with codebases big99and small. If you find an obstacle in your way, caused by Flask, don't hesitate100to contact the developers on the mailinglist or IRC channel. The best way for100to contact the developers on the mailing list or IRC channel. The best way for101the Flask and Flask extension developers to improve the tools for larger102applications is getting feedback from users.
modified:docs/blueprints.rst+8 added-9 removed
244 unmodified lines
245246Error Handlers247--------------248249Blueprints support the errorhandler decorator just like the :class:`Flask`249Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`250application object, so it is easy to make Blueprint-specific custom error251pages.252253Here is an example for a "404 Page Not Found" exception::
3 unmodified lines
257 return render_template('pages/404.html')258259Most errorhandlers will simply work as expected; however, there is a caveat260concerning handlers for 404 and 405 exceptions. These errorhandlers are only261invoked from an appropriate ``raise`` statement or a call to ``abort``262in another of the blueprint's view functions; they are not invoked by,263e.g., an invalid URL access. This is because the blueprint does not264"own" a certain URL space, so the application instance has no way of265knowing which blueprint errorhandler it should run if given an invalid URL.266If you would like to execute different handling strategies for these errors267based on URL prefixes, they may be defined at the application level using268the ``request`` proxy object::261invoked from an appropriate ``raise`` statement or a call to ``abort`` in another262of the blueprint's view functions; they are not invoked by, e.g., an invalid URL263access. This is because the blueprint does not "own" a certain URL space, so264the application instance has no way of knowing which blueprint error handler it265should run if given an invalid URL. If you would like to execute different266handling strategies for these errors based on URL prefixes, they may be defined267at the application level using the ``request`` proxy object::268269 @app.errorhandler(404)270 @app.errorhandler(405)271 def _handle_api_error(ex):
6 unmodified lines
modified:docs/cli.rst+3 added-3 removed
66 unmodified lines
67``FLASK_APP="hello:create_app('dev')"``68 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``69 as the argument.7071If ``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 or73factory.71If ``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 application73instance or factory.7475Within the given import, the command looks for an application instance named76``app`` or ``application``, then any application instance. If no instance is77found, the command looks for a factory function named ``create_app`` or
391 unmodified lines
modified:docs/config.rst+12 added-14 removed
7 unmodified lines
8toggling the debug mode, setting the secret key, and other such9environment-specific things.1011The way Flask is designed usually requires the configuration to be12available when the application starts up. You can hardcode the12available when the application starts up. You can hard code the13configuration in the code, which for many small applications is not14actually that bad, but there are better ways.1516Independent of how you load your config, there is a config object
419 unmodified lines
436methods on the config object as well to load from individual files. For a437complete reference, read the :class:`~flask.Config` object's438documentation.439440441Configuring from Environment Variables442--------------------------------------443444In addition to pointing to configuration files using environment variables, you
3 unmodified lines
448Environment variables can be set on Linux or OS X with the export command in449the shell before starting the server::450451 $ 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...455456On Windows systems use the `set` builtin instead::456On Windows systems use the ``set`` builtin instead::457458 > set SECRET_KEY='5f352379324c22463451387a0aec5d2f'459 > set DEBUG=False459460While this approach is straightforward to use, it is important to remember that461environment variables are strings -- they are not automatically deserialized462into Python types.463464Here is an example of a configuration file that uses environment variables::465467 # Example configuration466 import os467470 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"}470474 DEBUG = ENVIRONMENT_DEBUG475 SECRET_KEY = os.environ.get("SECRET_KEY", default=None)471 SECRET_KEY = os.environ.get("SECRET_KEY")472473 if not SECRET_KEY:477 raise ValueError("No secret key set for Flask application")474 raise ValueError("No SECRET_KEY set for Flask application")475476477Notice that any value besides an empty string will be interpreted as a boolean478``True`` value in Python, which requires care if an environment explicitly sets
3 unmodified lines
482ability to access the configuration when starting up. There are other methods483on the config object as well to load from individual files. For a complete484reference, read the :class:`~flask.Config` class documentation.485486487Configuration Best Practices488----------------------------489490The downside with the approach mentioned earlier is that it makes testing
2 unmodified lines
493that experience:4944951. 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.4995002. Do not write code that needs the configuration at import time. If you501 limit yourself to request-only accesses to the configuration you can
24 unmodified lines
526the config file by adding ``from yourapplication.default_settings527import *`` to the top of the file and then overriding the changes by hand.528You could also inspect an environment variable like529``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc532and import different hardcoded files based on that.530and import different hard-coded files based on that.531532An interesting pattern is also to use classes and inheritance for533configuration::534
160 unmodified lines
modified:docs/design.rst+2 added-2 removed
39 unmodified lines
40the time. There are ways to fake multiple applications with a single41application object, like maintaining a stack of applications, but this42causes some problems I won't outline here in detail. Now the question is:43when does a microframework need more than one application at the same44time? A good example for this is unittesting. When you want to test44time? A good example for this is unit testing. When you want to test45something it can be very helpful to create a minimal application to test46specific behavior. When the application object is deleted everything it47allocated will be freed again.48
26 unmodified lines
75there are better ways to do that so that you do not lose the reference76to the application object :meth:`~flask.Flask.wsgi_app`).7778Furthermore this design makes it possible to use a factory function to79create the application which is very helpful for unittesting and similar79create the application which is very helpful for unit testing and similar80things (:ref:`app-factories`).8182The Routing System83------------------
108 unmodified lines
modified:docs/extensiondev.rst+1 added-1 removed
285 unmodified lines
286also avoids having multiple developers working in isolation on pretty much the287same problem.288289Remember: good API design is hard, so introduce your project on the290mailinglist, and let other developers give you a helping hand with290mailing list, and let other developers give you a helping hand with291designing the API.292293The best Flask extensions are extensions that share common idioms for the294API. And this can only work if collaboration happens early.
51 unmodified lines
modified:docs/extensions.rst+1 added-1 removed
4 unmodified lines
56Extensions are extra packages that add functionality to a Flask7application. For example, an extension might add support for sending8email or connecting to a database. Some extensions add entire new9frameworks to help build certain types of applications, like a ReST API.9frameworks to help build certain types of applications, like a REST API.101112Finding Extensions13------------------
40 unmodified lines
modified:docs/quickstart.rst+8 added-8 removed
201 unmodified lines
202203 @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)207208 @app.route('/post/<int:post_id>')209 def show_post(post_id):210 # show the post with the given id, the id is an integer
1 unmodified line
212213 @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)217218Converter types:219220========== ==========================================
59 unmodified lines
280Python shell. See :ref:`context-locals`.281282.. code-block:: python283284 from flask import Flask, url_for284 from flask import Flask, escape, url_for285286 app = Flask(__name__)287288 @app.route('/')
5 unmodified lines
294 return 'login'295296 @app.route('/user/<username>')297 def profile(username):298 return '{}\'s profile'.format(username)298 return '{}\'s profile'.format(escape(username))299300 with app.test_request_context():301 print(url_for('index'))302 print(url_for('login'))
386 unmodified lines
6891. If a response object of the correct type is returned it's directly690 returned from the view.6912. If it's a string, a response object is created with that data and the692 default parameters.6933. 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 code6933. 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.6984. 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 lines
modified:docs/shell.rst+1 added-1 removed
18 unmodified lines
19can you do?2021This is where some helper functions come in handy. Keep in mind however22that these functions are not only there for interactive shell usage, but23also for unittesting and other situations that require a faked request23also for unit testing and other situations that require a faked request24context.2526Generally it's recommended that you read the :ref:`request-context`27chapter of the documentation first.
76 unmodified lines
modified:docs/unicode.rst+2 added-2 removed
41 unmodified lines
4243So the rule of thumb: if you are not dealing with binary data, work with44Unicode. What does working with Unicode in Python 2.x mean?4546- 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 lines
modified:flask/ctx.py+1 added-1 removed
173 unmodified lines
174 remote_addr = request.remote_addr175 self.remote_addr = remote_addr176177 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::179180 class User(db.Model):181182 def __init__(self, username, remote_addr=None):
291 unmodified lines
modified:flask/helpers.py+1 added-1 removed
276 unmodified lines
277 :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 no
816 unmodified lines
modified:CONTRIBUTING.rst+18 added-5 removed
7 unmodified lines
89Please, don't use the issue tracker for this. Use one of the following10resources for questions about your own code:1112* 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 lines
8182Start coding83~~~~~~~~~~~~8484- 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::8889 git checkout -b your-branch-name origin/1.0.x9091 If you're submitting a feature addition or change, branch off of the92 "master" branch::9394 git checkout -b your-branch-name origin/master9596- 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::102103 git push --set-upstream origin your-branch-name104105- Celebrate 🎉106107.. _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 lines
modified:README.rst+1 added
73 unmodified lines
74* Issue tracker: https://github.com/pallets/flask/issues75* Test status: https://dev.azure.com/pallets/pallets/_build?definitionId=27677* Test coverage: https://codecov.io/gh/pallets/flask78* Official chat: https://discord.gg/t6rrQZH7980.. _WSGI: https://wsgi.readthedocs.io81.. _Werkzeug: https://www.palletsprojects.com/p/werkzeug/82.. _Jinja: https://www.palletsprojects.com/p/jinja/
1 unmodified line