Merge branch 'master' into json-object-hook
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 d911c89, c7f433c · Browse files · 43 files·+1169 added−731 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
43 files+1169 added−731 removed
- tests:+142 added−39 removed
- other:+1027 added−692 removed
Provenance
- Commit
ea2e960- Tree
790f93e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
d911c89- Parent 2
c7f433c
43 files changed+1169 added−731 removed
modified:.github/ISSUE_TEMPLATE.rst+33 added-2 removed
1-The issue tracker is a tool to address bugs.2-Please use the #pocoo IRC channel on freenode or Stack Overflow for questions.1+**This issue tracker is a tool to address bugs in Flask itself.2+Please use the #pocoo IRC channel on freenode or Stack Overflow for general3+questions about using Jinja or issues not related to Jinja.**4+5+If you'd like to report a bug in Flask, fill out the template below. Provide6+any any extra information that may be useful / related to your problem.7+Ideally, create an [MCVE](http://stackoverflow.com/help/mcve), which helps us8+understand the problem and helps check that it is not caused by something in9+your code.10+11+---12+13+### Expected Behavior14+15+Tell us what should happen.16+17+```python18+Paste a minimal example that causes the problem.19+```20+21+### Actual Behavior22+23+Tell us what happens instead.24+25+```pytb26+Paste the full traceback if there was an exception.27+```28+29+### Environment30+31+* Python version:32+* Flask version:33+* Werkzeug version:added:.github/PULL_REQUEST_TEMPLATE.rst+16 added
1+Describe what this patch does to fix the issue.2+3+Link to any relevant issues or pull requests.4+5+<!--6+Commit checklist:7+8+* add tests that fail without the patch9+* ensure all tests pass with ``pytest``10+* add documentation to the relevant docstrings or pages11+* add ``versionadded`` or ``versionchanged`` directives to relevant docstrings12+* add a changelog entry if this patch changes code13+14+Tests, coverage, and docs will be run automatically when you submit the pull15+request, but running them yourself can save time.16+-->deleted:docs/_themesnot shown
Its text is not shown, deleted.
modified:docs/appcontext.rst+27 added-21 removed
3 unmodified lines4 =======================5 6 .. versionadded:: 0.97 8-One of the design ideas behind Flask is that there are two different9-“states” in which code is executed. The application setup state in which10-the application implicitly is on the module level. It starts when the11-:class:`Flask` object is instantiated, and it implicitly ends when the12-first request comes in. While the application is in this state a few13-assumptions are true:8+One of the design ideas behind Flask is that there are at least two9+different “states” in which code is executed:10 15-- the programmer can modify the application object safely.16-- no request handling happened so far17-- you have to have a reference to the application object in order to18- modify it, there is no magic proxy that can give you a reference to19- the application object you're currently creating or modifying.11+1. The application setup state, in which the application implicitly is12+on the module level.13 21-In contrast, during request handling, a couple of other rules exist:14+ This state starts when the :class:`Flask` object is instantiated, and15+ it implicitly ends when the first request comes in. While the16+ application is in this state, a few assumptions are true:17 23-- while a request is active, the context local objects24- (:data:`flask.request` and others) point to the current request.25-- any code can get hold of these objects at any time.18+ - the programmer can modify the application object safely.19+ - no request handling happened so far20+ - you have to have a reference to the application object in order to21+ modify it, there is no magic proxy that can give you a reference to22+ the application object you're currently creating or modifying.23 27-There is a third state which is sitting in between a little bit.28-Sometimes you are dealing with an application in a way that is similar to29-how you interact with applications during request handling; just that there30-is no request active. Consider, for instance, that you're sitting in an31-interactive Python shell and interacting with the application, or a32-command line application.24+2. In contrast, in the request handling state, a couple of other rules25+exist:26 27+ - while a request is active, the context local objects28+ (:data:`flask.request` and others) point to the current request.29+ - any code can get hold of these objects at any time.30+31+3. There is also a third state somewhere in between 'module-level' and32+'request-handling':33+34+ Sometimes you are dealing with an application in a way that is similar to35+ how you interact with applications during request handling, but without36+ there being an active request. Consider, for instance, that you're37+ sitting in an interactive Python shell and interacting with the38+ application, or a command line application.39+40 The application context is what powers the :data:`~flask.current_app`41 context local.42 43 Purpose of the Application Context101 unmodified linesmodified:docs/conf.py+4 added-17 removed
20 unmodified lines21 22 # If extensions (or modules to document with autodoc) are in another directory,23 # add these directories to sys.path here. If the directory is relative to the24 # documentation root, use os.path.abspath to make it absolute, like shown here.25-sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))25 sys.path.append(os.path.dirname(__file__))26 27 # -- General configuration -----------------------------------------------------28 90 unmodified lines119 # documentation.120 # html_theme_options = {}121 122 # Add any paths that contain custom themes here, relative to this directory.124-html_theme_path = ['_themes']123+# html_theme_path = ['_themes']124 125 # The name for this set of Sphinx documents. If None, it defaults to126 # "<project> v<release> documentation".127 #html_title = None143 unmodified lines271 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),272 'blinker': ('https://pythonhosted.org/blinker/', None)273 }274 276-try:277- __import__('flask_theme_support')278- pygments_style = 'flask_theme_support.FlaskyStyle'279- html_theme = 'flask'280- html_theme_options = {281- 'touch_icon': 'touch-icon.png'282- }275+html_theme_options = {276+ 'touch_icon': 'touch-icon.png'277+}283-except ImportError:284- print('-' * 74)285- print('Warning: Flask themes unavailable. Building with default theme')286- print('If you want the Flask themes, run this command and build again:')287- print()288- print(' git submodule update --init')289- print('-' * 74)278 291-279 # unwrap decorators280 def unwrap_decorators():281 import sphinx.util.inspect as inspect282 import functools15 unmodified linesmodified:docs/config.rst+236 added-166 removed
1 unmodified line2 3 Configuration Handling4 ======================5 6-.. versionadded:: 0.37-6 Applications need some kind of configuration. There are different settings7 you might want to change depending on the application environment like8 toggling the debug mode, setting the secret key, and other such9 environment-specific things.41 unmodified lines51 $ export FLASK_DEBUG=152 $ flask run53 54 (On Windows you need to use ``set`` instead of ``export``).57- 58- ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 55+56+ ``app.debug`` and ``app.config['DEBUG']`` are not compatible with57 the :command:`flask` script. They only worked when using ``Flask.run()``58 method.61- 59+60 Builtin Configuration Values61 ----------------------------62 63 The following configuration values are used internally by Flask:64 67-.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|65+.. py:data:: DEBUG66 69-================================= =========================================70-``DEBUG`` enable/disable debug mode when using 71- ``Flask.run()`` method to start server72-``TESTING`` enable/disable testing mode73-``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74- propagation of exceptions. If not set or75- explicitly set to ``None`` this is76- implicitly true if either ``TESTING`` or77- ``DEBUG`` is true.78-``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in79- debug mode the request context is not80- popped on exceptions to enable debuggers81- to introspect the data. This can be82- disabled by this key. You can also use83- this setting to force-enable it for non84- debug execution which might be useful to85- debug production applications (but also86- very risky).87-``SECRET_KEY`` the secret key88-``SESSION_COOKIE_NAME`` the name of the session cookie89-``SESSION_COOKIE_DOMAIN`` the domain for the session cookie. If90- this is not set, the cookie will be91- valid for all subdomains of92- ``SERVER_NAME``.93-``SESSION_COOKIE_PATH`` the path for the session cookie. If94- this is not set the cookie will be valid95- for all of ``APPLICATION_ROOT`` or if96- that is not set for ``'/'``.97-``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set98- with the httponly flag. Defaults to99- ``True``.100-``SESSION_COOKIE_SECURE`` controls if the cookie should be set101- with the secure flag. Defaults to102- ``False``.103-``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as104- :class:`datetime.timedelta` object.105- Starting with Flask 0.8 this can also be106- an integer representing seconds.107-``SESSION_REFRESH_EACH_REQUEST`` this flag controls how permanent108- sessions are refreshed. If set to ``True``109- (which is the default) then the cookie110- is refreshed each request which111- automatically bumps the lifetime. If112- set to ``False`` a `set-cookie` header is113- only sent if the session is modified.114- Non permanent sessions are not affected115- by this.116-``USE_X_SENDFILE`` enable/disable x-sendfile117-``LOGGER_NAME`` the name of the logger118-``LOGGER_HANDLER_POLICY`` the policy of the default logging119- handler. The default is ``'always'``120- which means that the default logging121- handler is always active. ``'debug'``122- will only activate logging in debug123- mode, ``'production'`` will only log in124- production and ``'never'`` disables it125- entirely.126-``SERVER_NAME`` the name and port number of the server.127- Required for subdomain support (e.g.:128- ``'myapp.dev:5000'``) Note that129- localhost does not support subdomains so130- setting this to “localhost” does not131- help. Setting a ``SERVER_NAME`` also132- by default enables URL generation133- without a request context but with an134- application context.135-``APPLICATION_ROOT`` The path value used for the session136- cookie if ``SESSION_COOKIE_PATH`` isn't137- set. If it's also ``None`` ``'/'`` is used.138- Note that to actually serve your Flask139- app under a subpath you need to tell140- your WSGI container the ``SCRIPT_NAME``141- WSGI environment variable.142-``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will143- reject incoming requests with a144- content length greater than this by145- returning a 413 status code.146-``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with147- :meth:`~flask.Flask.send_static_file` (the148- default static file handler) and149- :func:`~flask.send_file`, as150- :class:`datetime.timedelta` or as seconds.151- Override this value on a per-file152- basis using the153- :meth:`~flask.Flask.get_send_file_max_age`154- hook on :class:`~flask.Flask` or155- :class:`~flask.Blueprint`,156- respectively. Defaults to 43200 (12 hours).157-``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will158- not execute the error handlers of HTTP159- exceptions but instead treat the160- exception like any other and bubble it161- through the exception stack. This is162- helpful for hairy debugging situations163- where you have to find out where an HTTP164- exception is coming from.165-``TRAP_BAD_REQUEST_ERRORS`` Werkzeug's internal data structures that166- deal with request specific data will167- raise special key errors that are also168- bad request exceptions. Likewise many169- operations can implicitly fail with a170- BadRequest exception for consistency.171- Since it's nice for debugging to know172- why exactly it failed this flag can be173- used to debug those situations. If this174- config is set to ``True`` you will get175- a regular traceback instead.176-``PREFERRED_URL_SCHEME`` The URL scheme that should be used for177- URL generation if no URL scheme is178- available. This defaults to ``http``.179-``JSON_AS_ASCII`` By default Flask serialize object to180- ascii-encoded JSON. If this is set to181- ``False`` Flask will not encode to ASCII182- and output strings as-is and return183- unicode strings. ``jsonify`` will184- automatically encode it in ``utf-8``185- then for transport for instance.186-``JSON_SORT_KEYS`` By default Flask will serialize JSON187- objects in a way that the keys are188- ordered. This is done in order to189- ensure that independent of the hash seed190- of the dictionary the return value will191- be consistent to not trash external HTTP192- caches. You can override the default193- behavior by changing this variable.194- This is not recommended but might give195- you a performance improvement on the196- cost of cacheability.197-``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` or the Flask app198- is running in debug mode, jsonify responses199- will be pretty printed.200-``JSONIFY_MIMETYPE`` MIME type used for jsonify responses.201-``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of202- the template source and reload it203- automatically. By default the value is204- ``None`` which means that Flask checks205- original file only in debug mode.206-``EXPLAIN_TEMPLATE_LOADING`` If this is enabled then every attempt to207- load a template will write an info208- message to the logger explaining the209- attempts to locate the template. This210- can be useful to figure out why211- templates cannot be found or wrong212- templates appear to be loaded.213-================================= =========================================67+ Enable debug mode. When using the development server with ``flask run`` or68+ ``app.run``, an interactive debugger will be shown for unhanlded69+ exceptions, and the server will be reloaded when code changes.70 215-.. admonition:: More on ``SERVER_NAME``71+ **Do not enable debug mode in production.**72 217- The ``SERVER_NAME`` key is used for the subdomain support. Because218- Flask cannot guess the subdomain part without the knowledge of the219- actual server name, this is required if you want to work with220- subdomains. This is also used for the session cookie.73+ Default: ``False``74 222- Please keep in mind that not only Flask has the problem of not knowing223- what subdomains are, your web browser does as well. Most modern web224- browsers will not allow cross-subdomain cookies to be set on a225- server name without dots in it. So if your server name is226- ``'localhost'`` you will not be able to set a cookie for227- ``'localhost'`` and every subdomain of it. Please choose a different228- server name in that case, like ``'myapplication.local'`` and add229- this name + the subdomains you want to use into your host config230- or setup a local `bind`_.75+.. py:data:: TESTING76 232-.. _bind: https://www.isc.org/downloads/bind/77+ Enable testing mode. Exceptions are propagated rather than handled by the78+ the app's error handlers. Extensions may also change their behavior to79+ facilitate easier testing. You should enable this in your own tests.80 81+ Default: ``False``82+83+.. py:data:: PROPAGATE_EXCEPTIONS84+85+ Exceptions are re-raised rather than being handled by the app's error86+ handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``87+ is enabled.88+89+ Default: ``None``90+91+.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION92+93+ Don't pop the request context when an exception occurs. If not set, this94+ is true if ``DEBUG`` is true. This allows debuggers to introspect the95+ request data on errors, and should normally not need to be set directly.96+97+ Default: ``None``98+99+.. py:data:: TRAP_HTTP_EXCEPTIONS100+101+ If there is no handler for an ``HTTPException``-type exception, re-raise it102+ to be handled by the interactive debugger instead of returning it as a103+ simple error response.104+105+ Default: ``False``106+107+.. py:data:: TRAP_BAD_REQUEST_ERRORS``108+109+ Trying to access a key that doesn't exist from request dicts like ``args``110+ and ``form`` will return a 400 Bad Request error page. Enable this to treat111+ the error as an unhandled exception instead so that you get the interactive112+ debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If113+ unset, it is enabled in debug mode.114+115+ Default: ``None``116+117+.. py:data:: SECRET_KEY118+119+ A secret key that will be used for securely signing the session cookie120+ and can be used for any other security related needs by extensions or your121+ application. It should be a long random string of bytes, although unicode122+ is accepted too. For example, copy the output of this to your config::123+124+ python -c 'import os; print(os.urandom(32))'125+126+ **Do not reveal the secret key when posting questions or committing code.**127+128+ Default: ``None``129+130+.. py:data:: SESSION_COOKIE_NAME131+132+ The name of the session cookie. Can be changed in case you already have a133+ cookie with the same name.134+135+ Default: ``'session'``136+137+.. py:data:: SESSION_COOKIE_DOMAIN138+139+ The domain match rule that the session cookie will be valid for. If not140+ set, the cookie will be valid for all subdomains of ``SERVER_NAME``. If141+ ``False``, the cookie's domain will not be set.142+143+ Default: ``None``144+145+.. py:data:: SESSION_COOKIE_PATH146+147+ The path that the session cookie will be valid for. If not set, the cookie148+ will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.149+150+ Default: ``None``151+152+.. py:data:: SESSION_COOKIE_HTTPONLY153+154+ Browsers will not allow JavaScript access to cookies marked as "HTTP only"155+ for security.156+157+ Default: ``True``158+159+.. py:data:: SESSION_COOKIE_SECURE160+161+ Browsers will only send cookies with requests over HTTPS if the cookie is162+ marked "secure". The application must be served over HTTPS for this to make163+ sense.164+165+ Default: ``False``166+167+.. py:data:: PERMANENT_SESSION_LIFETIME168+169+ If ``session.permanent`` is true, the cookie's max age will be set to this170+ number of seconds. Can either be a :class:`datetime.timedelta` or an171+ ``int``.172+173+ Default: ``timedelta(days=31)`` (``2678400`` seconds)174+175+.. py:data:: SESSION_REFRESH_EACH_REQUEST176+177+ Control whether the cookie is sent with every response when178+ ``session.permanent`` is true. Sending the cookie every time (the default)179+ can more reliably keep the session from expiring, but uses more bandwidth.180+ Non-permanent sessions are not affected.181+182+ Default: ``True``183+184+.. py:data:: USE_X_SENDFILE185+186+ When serving files, set the ``X-Sendfile`` header instead of serving the187+ data with Flask. Some web servers, such as Apache, recognize this and serve188+ the data more efficiently. This only makes sense when using such a server.189+190+ Default: ``False``191+192+.. py:data:: SEND_FILE_MAX_AGE_DEFAULT193+194+ When serving files, set the cache control max age to this number of195+ seconds. Can either be a :class:`datetime.timedelta` or an ``int``.196+ Override this value on a per-file basis using197+ :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.198+199+ Default: ``timedelta(hours=12)`` (``43200`` seconds)200+201+.. py:data:: LOGGER_NAME202+203+ The name of the logger that the Flask application sets up. If not set,204+ it will take the import name passed to ``Flask.__init__``.205+206+ Default: ``None``207+208+.. py:data:: LOGGER_HANDLER_POLICY209+210+ When to activate the application's logger handler. ``'always'`` always211+ enables it, ``'debug'`` only activates it in debug mode, ``'production'``212+ only activates it when not in debug mode, and ``'never'`` never enables it.213+214+ Default: ``'always'``215+216+.. py:data:: SERVER_NAME217+218+ Inform the application what host and port it is bound to. Required for219+ subdomain route matching support.220+221+ If set, will be used for the session cookie domain if222+ ``SESSION_COOKIE_DOMAIN`` is not set. Modern web browsers will not allow223+ setting cookies for domains without a dot. To use a domain locally,224+ add any names that should route to the app to your ``hosts`` file. ::225+226+ 127.0.0.1 localhost.dev227+228+ If set, ``url_for`` can generate external URLs with only an application229+ context instead of a request context.230+231+ Default: ``None``232+233+.. py:data:: APPLICATION_ROOT234+235+ Inform the application what path it is mounted under by the application /236+ web server.237+238+ Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not239+ set.240+241+ Default: ``'/'``242+243+.. py:data:: PREFERRED_URL_SCHEME244+245+ Use this scheme for generating external URLs when not in a request context.246+247+ Default: ``'http'``248+249+.. py:data:: MAX_CONTENT_LENGTH250+251+ Don't read more than this many bytes from the incoming request data. If not252+ set and the request does not specify a ``CONTENT_LENGTH``, no data will be253+ read for security.254+255+ Default: ``None``256+257+.. py:data:: JSON_AS_ASCII258+259+ Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON260+ will be returned as a Unicode string, or encoded as ``UTF-8`` by261+ ``jsonify``. This has security implications when rendering the JSON in262+ to JavaScript in templates, and should typically remain enabled.263+264+ Default: ``True``265+266+.. py:data:: JSON_SORT_KEYS267+268+ Sort the keys of JSON objects alphabetically. This is useful for caching269+ because it ensures the data is serialized the same way no matter what270+ Python's hash seed is. While not recommended, you can disable this for a271+ possible performance improvement at the cost of caching.272+273+ Default: ``True``274+275+.. py:data:: JSONIFY_PRETTYPRINT_REGULAR276+277+ ``jsonify`` responses will be output with newlines, spaces, and indentation278+ for easier reading by humans. Always enabled in debug mode.279+280+ Default: ``False``281+282+.. py:data:: JSONIFY_MIMETYPE283+284+ The mimetype of ``jsonify`` responses.285+286+ Default: ``'application/json'``287+288+.. py:data:: TEMPLATES_AUTO_RELOAD289+290+ Reload templates when they are changed. If not set, it will be enabled in291+ debug mode.292+293+ Default: ``None``294+295+.. py:data:: EXPLAIN_TEMPLATE_LOADING296+297+ Log debugging information tracing how a template file was loaded. This can298+ be useful to figure out why a template was not loaded or the wrong file299+ appears to be loaded.300+301+ Default: ``False``302+303 .. versionadded:: 0.4304 ``LOGGER_NAME``305 306 .. versionadded:: 0.5238 unmodified lines545 546 # or via open_instance_resource:547 with app.open_instance_resource('application.cfg') as f:548 config = f.read()549+modified:docs/contents.rst.inc+1 added
57 unmodified lines58 python359 upgrading60 changelog61 license62+ contributingadded:docs/contributing.rst+1 added
1+.. include:: ../CONTRIBUTING.rstmodified:docs/errorhandling.rst+47 added-24 removed
74 unmodified lines75 76 You might want to show custom error pages to the user when an error occurs.77 This can be done by registering error handlers.78 79-Error handlers are normal :ref:`views` but instead of being registered for80-routes, they are registered for exceptions that are raised while trying to81-do something else.79+An error handler is a normal view function that return a response, but instead80+of being registered for a route, it is registered for an exception or HTTP81+status code that would is raised while trying to handle a request.82 83 Registering84 ```````````85 86-Register error handlers using :meth:`~flask.Flask.errorhandler` or87-:meth:`~flask.Flask.register_error_handler`::86+Register handlers by decorating a function with87+:meth:`~flask.Flask.errorhandler`. Or use88+:meth:`~flask.Flask.register_error_handler` to register the function later.89+Remember to set the error code when returning the response. ::90 91 @app.errorhandler(werkzeug.exceptions.BadRequest)92 def handle_bad_request(e):91- return 'bad request!'93+ return 'bad request!', 40094 95+ # or, without the decorator93- app.register_error_handler(400, lambda e: 'bad request!')96+ app.register_error_handler(400, handle_bad_request)97 95-Those two ways are equivalent, but the first one is more clear and leaves96-you with a function to call on your whim (and in tests). Note that98 :exc:`werkzeug.exceptions.HTTPException` subclasses like98-:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes99-are interchangeable when handed to the registration methods or decorator100-(``BadRequest.code == 400``).99+:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable100+when registering handlers. (``BadRequest.code == 400``)101 102-You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103-or HTTP status codes but can register a handler for every exception class you104-like.102+Non-standard HTTP codes cannot be registered by code because they are not known103+by Werkzeug. Instead, define a subclass of104+:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105+register and raise that exception class. ::106 106-.. versionchanged:: 0.11107+ class InsufficientStorage(werkzeug.exceptions.HTTPException):108+ code = 507109+ description = 'Not enough storage space.'110 108- Errorhandlers are now prioritized by specificity of the exception classes109- they are registered for instead of the order they are registered in.111+ app.register_error_handler(InsuffcientStorage, handle_507)112 113+ raise InsufficientStorage()114+115+Handlers can be registered for any exception class, not just116+:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status117+codes. Handlers can be registered for a specific class, or for all subclasses118+of a parent class.119+120 Handling121 ````````122 114-Once an exception instance is raised, its class hierarchy is traversed,115-and searched for in the exception classes for which handlers are registered.116-The most specific handler is selected.123+When an exception is caught by Flask while handling a request, it is first124+looked up by code. If no handler is registered for the code, it is looked up125+by its class hierarchy; the most specific handler is chosen. If no handler is126+registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a127+generic message about their code, while other exceptions are converted to a128+generic 500 Internal Server Error.129 118-E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler130+For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler131 is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120-the more specific :exc:`ConnectionRefusedError` handler is called on the121-exception instance, and its response is shown to the user.132+the more specific :exc:`ConnectionRefusedError` handler is called with the133+exception instance to generate the response.134 135+Handlers registered on the blueprint take precedence over those registered136+globally on the application, assuming a blueprint is handling the request that137+raises the exception. However, the blueprint cannot handle 404 routing errors138+because the 404 occurs at the routing level before the blueprint can be139+determined.140+141+.. versionchanged:: 0.11142+143+ Handlers are prioritized by specificity of the exception classes they are144+ registered for instead of the order they are registered in.145+146 Error Mails147 -----------148 149 If the application runs in production mode (which it will do on your268 unmodified linesdeleted:docs/flaskext.py-86 removed
1-# flasky extensions. flasky pygments style based on tango style2-from pygments.style import Style3-from pygments.token import Keyword, Name, Comment, String, Error, \4- Number, Operator, Generic, Whitespace, Punctuation, Other, Literal5-6-7-class FlaskyStyle(Style):8- background_color = "#f8f8f8"9- default_style = ""10-11- styles = {12- # No corresponding class for the following:13- #Text: "", # class: ''14- Whitespace: "underline #f8f8f8", # class: 'w'15- Error: "#a40000 border:#ef2929", # class: 'err'16- Other: "#000000", # class 'x'17-18- Comment: "italic #8f5902", # class: 'c'19- Comment.Preproc: "noitalic", # class: 'cp'20-21- Keyword: "bold #004461", # class: 'k'22- Keyword.Constant: "bold #004461", # class: 'kc'23- Keyword.Declaration: "bold #004461", # class: 'kd'24- Keyword.Namespace: "bold #004461", # class: 'kn'25- Keyword.Pseudo: "bold #004461", # class: 'kp'26- Keyword.Reserved: "bold #004461", # class: 'kr'27- Keyword.Type: "bold #004461", # class: 'kt'28-29- Operator: "#582800", # class: 'o'30- Operator.Word: "bold #004461", # class: 'ow' - like keywords31-32- Punctuation: "bold #000000", # class: 'p'33-34- # because special names such as Name.Class, Name.Function, etc.35- # are not recognized as such later in the parsing, we choose them36- # to look the same as ordinary variables.37- Name: "#000000", # class: 'n'38- Name.Attribute: "#c4a000", # class: 'na' - to be revised39- Name.Builtin: "#004461", # class: 'nb'40- Name.Builtin.Pseudo: "#3465a4", # class: 'bp'41- Name.Class: "#000000", # class: 'nc' - to be revised42- Name.Constant: "#000000", # class: 'no' - to be revised43- Name.Decorator: "#888", # class: 'nd' - to be revised44- Name.Entity: "#ce5c00", # class: 'ni'45- Name.Exception: "bold #cc0000", # class: 'ne'46- Name.Function: "#000000", # class: 'nf'47- Name.Property: "#000000", # class: 'py'48- Name.Label: "#f57900", # class: 'nl'49- Name.Namespace: "#000000", # class: 'nn' - to be revised50- Name.Other: "#000000", # class: 'nx'51- Name.Tag: "bold #004461", # class: 'nt' - like a keyword52- Name.Variable: "#000000", # class: 'nv' - to be revised53- Name.Variable.Class: "#000000", # class: 'vc' - to be revised54- Name.Variable.Global: "#000000", # class: 'vg' - to be revised55- Name.Variable.Instance: "#000000", # class: 'vi' - to be revised56-57- Number: "#990000", # class: 'm'58-59- Literal: "#000000", # class: 'l'60- Literal.Date: "#000000", # class: 'ld'61-62- String: "#4e9a06", # class: 's'63- String.Backtick: "#4e9a06", # class: 'sb'64- String.Char: "#4e9a06", # class: 'sc'65- String.Doc: "italic #8f5902", # class: 'sd' - like a comment66- String.Double: "#4e9a06", # class: 's2'67- String.Escape: "#4e9a06", # class: 'se'68- String.Heredoc: "#4e9a06", # class: 'sh'69- String.Interpol: "#4e9a06", # class: 'si'70- String.Other: "#4e9a06", # class: 'sx'71- String.Regex: "#4e9a06", # class: 'sr'72- String.Single: "#4e9a06", # class: 's1'73- String.Symbol: "#4e9a06", # class: 'ss'74-75- Generic: "#000000", # class: 'g'76- Generic.Deleted: "#a40000", # class: 'gd'77- Generic.Emph: "italic #000000", # class: 'ge'78- Generic.Error: "#ef2929", # class: 'gr'79- Generic.Heading: "bold #000080", # class: 'gh'80- Generic.Inserted: "#00A000", # class: 'gi'81- Generic.Output: "#888", # class: 'go'82- Generic.Prompt: "#745334", # class: 'gp'83- Generic.Strong: "bold #000000", # class: 'gs'84- Generic.Subheading: "bold #800080", # class: 'gu'85- Generic.Traceback: "bold #a40000", # class: 'gt'86- }modified:docs/security.rst+102 added
102 unmodified lines103 vulnerabilities104 <https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so105 this behavior was changed and :func:`~flask.jsonify` now supports serializing106 arrays.107+108+Security Headers109+----------------110+111+Browsers recognize various response headers in order to control security. We112+recommend reviewing each of the headers below for use in your application.113+The `Flask-Talisman`_ extension can be used to manage HTTPS and the security114+headers for you.115+116+.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman117+118+HTTP Strict Transport Security (HSTS)119+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~120+121+Tells the browser to convert all HTTP requests to HTTPS, preventing122+man-in-the-middle (MITM) attacks. ::123+124+ response.haders['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'125+126+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security127+128+Content Security Policy (CSP)129+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~130+131+Tell the browser where it can load various types of resource from. This header132+should be used whenever possible, but requires some work to define the correct133+policy for your site. A very strict policy would be::134+135+ response.headers['Content-Security-Policy'] = "default-src: 'self'"136+137+- https://csp.withgoogle.com/docs/index.html138+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy139+140+X-Content-Type-Options141+~~~~~~~~~~~~~~~~~~~~~~142+143+Forces the browser to honor the response content type instead of trying to144+detect it, which can be abused to generate a cross-site scripting (XSS)145+attack. ::146+147+ response.headers['X-Content-Type-Options'] = 'nosniff'148+149+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options150+151+X-Frame-Options152+~~~~~~~~~~~~~~~153+154+Prevents external sites from embedding your site in an ``iframe``. This155+prevents a class of attacks where clicks in the outer frame can be translated156+invisibly to clicks on your page's elements. This is also known as157+"clickjacking". ::158+159+ response.headers['X-Frame-Options'] = 'SAMEORIGIN'160+161+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options162+163+X-XSS-Protection164+~~~~~~~~~~~~~~~~165+166+The browser will try to prevent reflected XSS attacks by not loading the page167+if the request contains something that looks like JavaScript and the response168+contains the same data. ::169+170+ response.headers['X-XSS-Protection'] = '1; mode=block'171+172+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection173+174+Set-Cookie options175+~~~~~~~~~~~~~~~~~~176+177+These options can be added to a ``Set-Cookie`` header to improve their178+security. Flask has configuration options to set these on the session cookie.179+They can be set on other cookies too.180+181+- ``Secure`` limits cookies to HTTPS traffic only.182+- ``HttpOnly`` protects the contents of cookies from being read with183+ JavaScript.184+- ``SameSite`` ensures that cookies can only be requested from the same185+ domain that created them. It is not supported by Flask yet.186+187+::188+189+ app.config.update(190+ SESSION_COOKIE_SECURE=True,191+ SESSION_COOKIE_HTTPONLY=True,192+ )193+194+ response.set_cookie('username', 'flask', secure=True, httponly=True)195+196+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies197+198+HTTP Public Key Pinning (HPKP)199+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~200+201+This tells the browser to authenticate with the server using only the specific202+certificate key to prevent MITM attacks.203+204+.. warning::205+ Be careful when enabling this, as it is very difficult to undo if you set up206+ or upgrade your key incorrectly.207+208+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinningadded:examples/flaskr/flaskr/blueprints/__init__.py
added:examples/flaskr/flaskr/blueprints/flaskr.py+85 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+from sqlite3 import dbapi2 as sqlite314+from flask import Blueprint, request, session, g, redirect, url_for, abort, \15+ render_template, flash, current_app16+17+18+# create our blueprint :)19+bp = Blueprint('flaskr', __name__)20+21+22+def connect_db():23+ """Connects to the specific database."""24+ rv = sqlite3.connect(current_app.config['DATABASE'])25+ rv.row_factory = sqlite3.Row26+ return rv27+28+29+def init_db():30+ """Initializes the database."""31+ db = get_db()32+ with current_app.open_resource('schema.sql', mode='r') as f:33+ db.cursor().executescript(f.read())34+ db.commit()35+36+37+def get_db():38+ """Opens a new database connection if there is none yet for the39+ current application context.40+ """41+ if not hasattr(g, 'sqlite_db'):42+ g.sqlite_db = connect_db()43+ return g.sqlite_db44+45+46+@bp.route('/')47+def show_entries():48+ db = get_db()49+ cur = db.execute('select title, text from entries order by id desc')50+ entries = cur.fetchall()51+ return render_template('show_entries.html', entries=entries)52+53+54+@bp.route('/add', methods=['POST'])55+def add_entry():56+ if not session.get('logged_in'):57+ abort(401)58+ db = get_db()59+ db.execute('insert into entries (title, text) values (?, ?)',60+ [request.form['title'], request.form['text']])61+ db.commit()62+ flash('New entry was successfully posted')63+ return redirect(url_for('flaskr.show_entries'))64+65+66+@bp.route('/login', methods=['GET', 'POST'])67+def login():68+ error = None69+ if request.method == 'POST':70+ if request.form['username'] != current_app.config['USERNAME']:71+ error = 'Invalid username'72+ elif request.form['password'] != current_app.config['PASSWORD']:73+ error = 'Invalid password'74+ else:75+ session['logged_in'] = True76+ flash('You were logged in')77+ return redirect(url_for('flaskr.show_entries'))78+ return render_template('login.html', error=error)79+80+81+@bp.route('/logout')82+def logout():83+ session.pop('logged_in', None)84+ flash('You were logged out')85+ return redirect(url_for('flaskr.show_entries'))modified:examples/flaskr/flaskr/templates/layout.html+2 added-2 removed
3 unmodified lines4 <div class="page">5 <h1>Flaskr</h1>6 <div class="metanav">7 {% if not session.logged_in %}8- <a href="{{ url_for('login') }}">log in</a>8+ <a href="{{ url_for('flaskr.login') }}">log in</a>9 {% else %}10- <a href="{{ url_for('logout') }}">log out</a>10+ <a href="{{ url_for('flaskr.logout') }}">log out</a>11 {% endif %}12 </div>13 {% for message in get_flashed_messages() %}14 <div class="flash">{{ message }}</div>3 unmodified linesmodified:examples/flaskr/flaskr/templates/login.html+1 added-1 removed
1 {% extends "layout.html" %}2 {% block body %}3 <h2>Login</h2>4 {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5- <form action="{{ url_for('login') }}" method="post">5+ <form action="{{ url_for('flaskr.login') }}" method="post">6 <dl>7 <dt>Username:8 <dd><input type="text" name="username">9 <dt>Password:5 unmodified linesmodified:examples/flaskr/flaskr/templates/show_entries.html+1 added-1 removed
1 {% extends "layout.html" %}2 {% block body %}3 {% if session.logged_in %}4- <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">4+ <form action="{{ url_for('flaskr.add_entry') }}" method="post" class="add-entry">5 <dl>6 <dt>Title:7 <dd><input type="text" size="30" name="title">8 <dt>Text:13 unmodified linesmodified:examples/flaskr/flaskr/__init__.py-1 removed
1-from .flaskr import appadded:examples/flaskr/flaskr/factory.py+64 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+import os14+from flask import Flask, g15+from werkzeug.utils import find_modules, import_string16+from flaskr.blueprints.flaskr import init_db17+18+19+def create_app(config=None):20+ app = Flask('flaskr')21+22+ app.config.update(dict(23+ DATABASE=os.path.join(app.root_path, 'flaskr.db'),24+ DEBUG=True,25+ SECRET_KEY='development key',26+ USERNAME='admin',27+ PASSWORD='default'28+ ))29+ app.config.update(config or {})30+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)31+32+ register_blueprints(app)33+ register_cli(app)34+ register_teardowns(app)35+36+ return app37+38+39+def register_blueprints(app):40+ """Register all blueprint modules41+42+ Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.43+ """44+ for name in find_modules('flaskr.blueprints'):45+ mod = import_string(name)46+ if hasattr(mod, 'bp'):47+ app.register_blueprint(mod.bp)48+ return None49+50+51+def register_cli(app):52+ @app.cli.command('initdb')53+ def initdb_command():54+ """Creates the database tables."""55+ init_db()56+ print('Initialized the database.')57+58+59+def register_teardowns(app):60+ @app.teardown_appcontext61+ def close_db(error):62+ """Closes the database again at the end of the request."""63+ if hasattr(g, 'sqlite_db'):64+ g.sqlite_db.close()deleted:examples/flaskr/flaskr/flaskr.py-110 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr4- ~~~~~~5-6- A microblog example application written as Flask tutorial with7- Flask and sqlite3.8-9- :copyright: (c) 2015 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-13-import os14-from sqlite3 import dbapi2 as sqlite315-from flask import Flask, request, session, g, redirect, url_for, abort, \16- render_template, flash17-18-19-# create our little application :)20-app = Flask(__name__)21-22-# Load default config and override config from an environment variable23-app.config.update(dict(24- DATABASE=os.path.join(app.root_path, 'flaskr.db'),25- DEBUG=True,26- SECRET_KEY='development key',27- USERNAME='admin',28- PASSWORD='default'29-))30-app.config.from_envvar('FLASKR_SETTINGS', silent=True)31-32-33-def connect_db():34- """Connects to the specific database."""35- rv = sqlite3.connect(app.config['DATABASE'])36- rv.row_factory = sqlite3.Row37- return rv38-39-40-def init_db():41- """Initializes the database."""42- db = get_db()43- with app.open_resource('schema.sql', mode='r') as f:44- db.cursor().executescript(f.read())45- db.commit()46-47-48-@app.cli.command('initdb')49-def initdb_command():50- """Creates the database tables."""51- init_db()52- print('Initialized the database.')53-54-55-def get_db():56- """Opens a new database connection if there is none yet for the57- current application context.58- """59- if not hasattr(g, 'sqlite_db'):60- g.sqlite_db = connect_db()61- return g.sqlite_db62-63-64-@app.teardown_appcontext65-def close_db(error):66- """Closes the database again at the end of the request."""67- if hasattr(g, 'sqlite_db'):68- g.sqlite_db.close()69-70-71-@app.route('/')72-def show_entries():73- db = get_db()74- cur = db.execute('select title, text from entries order by id desc')75- entries = cur.fetchall()76- return render_template('show_entries.html', entries=entries)77-78-79-@app.route('/add', methods=['POST'])80-def add_entry():81- if not session.get('logged_in'):82- abort(401)83- db = get_db()84- db.execute('insert into entries (title, text) values (?, ?)',85- [request.form['title'], request.form['text']])86- db.commit()87- flash('New entry was successfully posted')88- return redirect(url_for('show_entries'))89-90-91-@app.route('/login', methods=['GET', 'POST'])92-def login():93- error = None94- if request.method == 'POST':95- if request.form['username'] != app.config['USERNAME']:96- error = 'Invalid username'97- elif request.form['password'] != app.config['PASSWORD']:98- error = 'Invalid password'99- else:100- session['logged_in'] = True101- flash('You were logged in')102- return redirect(url_for('show_entries'))103- return render_template('login.html', error=error)104-105-106-@app.route('/logout')107-def logout():108- session.pop('logged_in', None)109- flash('You were logged out')110- return redirect(url_for('show_entries'))modified:examples/flaskr/tests/test_flaskr.py+39 added-20 removed
10 unmodified lines11 12 import os13 import tempfile14 import pytest15-from flaskr import flaskr15+from flaskr.factory import create_app16+from flaskr.blueprints.flaskr import init_db17 18 19 @pytest.fixture19-def client():20- db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21- flaskr.app.config['TESTING'] = True22- client = flaskr.app.test_client()23- with flaskr.app.app_context():24- flaskr.init_db()25- yield client26- os.close(db_fd)27- os.unlink(flaskr.app.config['DATABASE'])20+def app(request):21 22+ db_fd, temp_db_location = tempfile.mkstemp()23+ config = {24+ 'DATABASE': temp_db_location,25+ 'TESTING': True,26+ 'DB_FD': db_fd27+ }28 29+ app = create_app(config=config)30+31+ with app.app_context():32+ init_db()33+ yield app34+35+36+@pytest.fixture37+def client(request, app):38+39+ client = app.test_client()40+41+ def teardown():42+ os.close(app.config['DB_FD'])43+ os.unlink(app.config['DATABASE'])44+ request.addfinalizer(teardown)45+46+ return client47+48+49 def login(client, username, password):50 return client.post('/login', data=dict(51 username=username,52 password=password9 unmodified lines62 rv = client.get('/')63 assert b'No entries here so far' in rv.data64 65 47-def test_login_logout(client):66+def test_login_logout(client, app):67 """Make sure login and logout works"""49- rv = login(client, flaskr.app.config['USERNAME'],50- flaskr.app.config['PASSWORD'])68+ rv = login(client, app.config['USERNAME'],69+ app.config['PASSWORD'])70 assert b'You were logged in' in rv.data71 rv = logout(client)72 assert b'You were logged out' in rv.data54- rv = login(client, flaskr.app.config['USERNAME'] + 'x',55- flaskr.app.config['PASSWORD'])73+ rv = login(client,app.config['USERNAME'] + 'x',74+ app.config['PASSWORD'])75 assert b'Invalid username' in rv.data57- rv = login(client, flaskr.app.config['USERNAME'],58- flaskr.app.config['PASSWORD'] + 'x')76+ rv = login(client, app.config['USERNAME'],77+ app.config['PASSWORD'] + 'x')78 assert b'Invalid password' in rv.data79 80 62-def test_messages(client):81+def test_messages(client, app):82 """Test that messages work"""64- login(client, flaskr.app.config['USERNAME'],65- flaskr.app.config['PASSWORD'])83+ login(client, app.config['USERNAME'],84+ app.config['PASSWORD'])85 rv = client.post('/add', data=dict(86 title='<Hello>',87 text='<strong>HTML</strong> allowed here'88 ), follow_redirects=True)3 unmodified linesmodified:examples/flaskr/README+5 added-3 removed
7 unmodified lines8 A sqlite powered thumble blog application9 10 ~ How do I use it?11 12- 1. edit the configuration in the flaskr.py file or12+ 1. edit the configuration in the factory.py file or13 export an FLASKR_SETTINGS environment variable14- pointing to a configuration file.14+ pointing to a configuration file or pass in a15+ dictionary with config values using the create_app16+ function.17 18 2. install the app from the root of the project directory19 20 pip install --editable .21 22 3. Instruct flask to use the right application23 22- export FLASK_APP=flaskr24+ export FLASK_APP=flaskr.factory:create_app()25 26 4. initialize the database with this command:27 28 flask initdb12 unmodified linesmodified:examples/flaskr/setup.cfg+2 added-2 removed
1-[tool:pytest]2-test=pytest1+[aliases]2+test=pytestmodified:examples/flaskr/setup.py+13 added-2 removed
1-from setuptools import setup1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5 6+ Tests the Flaskr application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+from setuptools import setup, find_packages13+14 setup(15 name='flaskr',5- packages=['flaskr'],16+ packages=find_packages(),17 include_package_data=True,18 install_requires=[19 'flask',20 ],7 unmodified linesmodified:examples/minitwit/minitwit/minitwit.py+1 added-1 removed
23 unmodified lines24 DEBUG = True25 SECRET_KEY = 'development key'26 27 # create our little application :)28-app = Flask(__name__)28+app = Flask('minitwit')29 app.config.from_object(__name__)30 app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31 32 224 unmodified linesmodified:examples/patterns/largerapp/yourapplication/__init__.py+2 added-2 removed
1 from flask import Flask2-app = Flask(__name__)2+app = Flask('yourapplication')3 4-import yourapplication.views4+import yourapplication.viewsmodified:flask/app.py+92 added-37 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13+import warnings14 from datetime import timedelta15 from functools import update_wrapper16 from itertools import chain17 from threading import Lock18 19 from werkzeug.datastructures import ImmutableDict, Headers20 from werkzeug.exceptions import BadRequest, HTTPException, \20- InternalServerError, MethodNotAllowed, default_exceptions21+ InternalServerError, MethodNotAllowed, default_exceptions, \22+ BadRequestKeyError23 from werkzeug.routing import BuildError, Map, RequestRedirect, Rule24 25 from . import cli, json26 from ._compat import integer_types, reraise, string_types, text_type281 unmodified lines308 'USE_X_SENDFILE': False,309 'LOGGER_NAME': None,310 'LOGGER_HANDLER_POLICY': 'always',311 'SERVER_NAME': None,310- 'APPLICATION_ROOT': None,312+ 'APPLICATION_ROOT': '/',313 'SESSION_COOKIE_NAME': 'session',314 'SESSION_COOKIE_DOMAIN': None,315 'SESSION_COOKIE_PATH': None,316 'SESSION_COOKIE_HTTPONLY': True,317 'SESSION_COOKIE_SECURE': False,318 'SESSION_REFRESH_EACH_REQUEST': True,319 'MAX_CONTENT_LENGTH': None,320 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),319- 'TRAP_BAD_REQUEST_ERRORS': False,321+ 'TRAP_BAD_REQUEST_ERRORS': None,322 'TRAP_HTTP_EXCEPTIONS': False,323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,600 unmodified lines926 session data in a signed cookie. This requires that the927 :attr:`secret_key` is set. Instead of overriding this method928 we recommend replacing the :class:`session_interface`.929 930+ .. deprecated: 1.0931+ Will be removed in 1.1. Use ``session_interface.open_session``932+ instead.933+934 :param request: an instance of :attr:`request_class`.935 """936+937+ warnings.warn(DeprecationWarning(938+ '"open_session" is deprecated and will be removed in 1.1. Use'939+ ' "session_interface.open_session" instead.'940+ ))941 return self.session_interface.open_session(self, request)942 943 def save_session(self, session, response):944 """Saves the session if it needs updates. For the default945 implementation, check :meth:`open_session`. Instead of overriding this946 method we recommend replacing the :class:`session_interface`.947 948+ .. deprecated: 1.0949+ Will be removed in 1.1. Use ``session_interface.save_session``950+ instead.951+952 :param session: the session to be saved (a953 :class:`~werkzeug.contrib.securecookie.SecureCookie`954 object)955 :param response: an instance of :attr:`response_class`956 """957+958+ warnings.warn(DeprecationWarning(959+ '"save_session" is deprecated and will be removed in 1.1. Use'960+ ' "session_interface.save_session" instead.'961+ ))962 return self.session_interface.save_session(self, session, response)963 964 def make_null_session(self):965 """Creates a new instance of a missing session. Instead of overriding966 this method we recommend replacing the :class:`session_interface`.967 968+ .. deprecated: 1.0969+ Will be removed in 1.1. Use ``session_interface.make_null_session``970+ instead.971+972 .. versionadded:: 0.7973 """974+975+ warnings.warn(DeprecationWarning(976+ '"make_null_session" is deprecated and will be removed in 1.1. Use'977+ ' "session_interface.make_null_session" instead.'978+ ))979 return self.session_interface.make_null_session(self)980 981 @setupmethod982 def register_blueprint(self, blueprint, **options):182 unmodified lines1165 return exc_class, None1166 1167 @setupmethod1168 def errorhandler(self, code_or_exception):1169+ """Register a function to handle errors by code or exception class.1170+1140- """A decorator that is used to register a function given an1171+ A decorator that is used to register a function given an1172 error code. Example::1173 1174 @app.errorhandler(404)1175 def page_not_found(error):4 unmodified lines1180 @app.errorhandler(DatabaseError)1181 def special_exception_handler(error):1182 return 'Database connection failed', 5001183 1153- You can also register a function as error handler without using1154- the :meth:`errorhandler` decorator. The following example is1155- equivalent to the one above::1156-1157- def page_not_found(error):1158- return 'This page does not exist', 4041159- app.error_handler_spec[None][404] = page_not_found1160-1161- Setting error handlers via assignments to :attr:`error_handler_spec`1162- however is discouraged as it requires fiddling with nested dictionaries1163- and the special case for arbitrary exception types.1164-1165- The first ``None`` refers to the active blueprint. If the error1166- handler should be application wide ``None`` shall be used.1167-1184 .. versionadded:: 0.71185 Use :meth:`register_error_handler` instead of modifying1186 :attr:`error_handler_spec` directly, for application wide error1187 handlers.10 unmodified lines1198 self._register_error_handler(None, code_or_exception, f)1199 return f1200 return decorator1201 1202+ @setupmethod1203 def register_error_handler(self, code_or_exception, f):1204 """Alternative error attach function to the :meth:`errorhandler`1205 decorator that is more straightforward to use for non decorator1206 usage.10 unmodified lines1217 :type f: callable1218 """1219 if isinstance(code_or_exception, HTTPException): # old broken behavior1220 raise ValueError(1204- 'Tried to register a handler for an exception instance {0!r}. '1205- 'Handlers can only be registered for exception classes or HTTP error codes.'1206- .format(code_or_exception))1221+ 'Tried to register a handler for an exception instance {0!r}.'1222+ ' Handlers can only be registered for exception classes or'1223+ ' HTTP error codes.'.format(code_or_exception)1224+ )1225 1226+ try:1208- exc_class, code = self._get_exc_class_and_code(code_or_exception)1227+ exc_class, code = self._get_exc_class_and_code(code_or_exception)1228+ except KeyError:1229+ raise KeyError(1230+ "'{0}' is not a recognized HTTP error code. Use a subclass of"1231+ " HTTPException with that code instead.".format(code_or_exception)1232+ )1233 1234 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1235 handlers[exc_class] = f1236 96 unmodified lines1333 1334 @setupmethod1335 def before_request(self, f):1336 """Registers a function to run before each request.1313- 1337+1338 For example, this can be used to open a database connection, or to load1339 the logged in user from the session.1340 1341 The function will be called without any arguments. If it returns a119 unmodified lines1461 def url_value_preprocessor(self, f):1462 """Register a URL value preprocessor function for all view1463 functions in the application. These functions will be called before the1464 :meth:`before_request` functions.1441- 1465+1466 The function can modify the values captured from the matched url before1467 they are passed to the view. For example, this can be used to pop a1468 common language code value and place it in ``g`` rather than pass it to1469 every view.1446- 1470+1471 The function is passed the endpoint name and values dict. The return1472 value is ignored.1473 """1474 self.url_value_preprocessors.setdefault(None, []).append(f)63 unmodified lines1538 exception is not called and it shows up as regular exception in the1539 traceback. This is helpful for debugging implicitly raised HTTP1540 exceptions.1541 1542+ .. versionchanged:: 1.01543+ Bad request errors are not trapped by default in debug mode.1544+1545 .. versionadded:: 0.81546 """1547 if self.config['TRAP_HTTP_EXCEPTIONS']:1548 return True1522- if self.config['TRAP_BAD_REQUEST_ERRORS']:1549+1550+ trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']1551+1552+ # if unset, trap based on debug mode1553+ if (trap_bad_request is None and self.debug) or trap_bad_request:1554 return isinstance(e, BadRequest)1555+1556 return False1557 1558 def handle_user_exception(self, e):1559 """This method is called whenever an exception occurs that should be2 unmodified lines1562 this function to the :meth:`handle_http_exception` method. This1563 function will either return a response value or reraise the1564 exception with the same traceback.1565 1566+ .. versionchanged:: 1.01567+ Key errors raised from request data like ``form`` show the the bad1568+ key in debug mode rather than a generic bad request message.1569+1570 .. versionadded:: 0.71571 """1572 exc_type, exc_value, tb = sys.exc_info()1573 assert exc_value is e1538-1574 # ensure not to trash sys.exc_info() at that point in case someone1575 # wants the traceback preserved in handle_http_exception. Of course1576 # we cannot prevent users from trashing it themselves in a custom1577 # trap_http_exception method so that's their fault then.1578 1579+ # MultiDict passes the key to the exception, but that's ignored1580+ # when generating the response message. Set an informative1581+ # description for key errors in debug mode or when trapping errors.1582+ if (1583+ (self.debug or self.config['TRAP_BAD_REQUEST_ERRORS'])1584+ and isinstance(e, BadRequestKeyError)1585+ # only set it if it's still the default description1586+ and e.description is BadRequestKeyError.description1587+ ):1588+ e.description = "KeyError: '{0}'".format(*e.args)1589+1590 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1591 return self.handle_http_exception(e)1592 1593 handler = self._find_error_handler(e)183 unmodified lines1777 1778 ``str`` (``unicode`` in Python 2)1779 A response object is created with the string encoded to UTF-81780 as the body.1735- 1781+1782 ``bytes`` (``str`` in Python 2)1783 A response object is created with the bytes as the body.1738- 1784+1785 ``tuple``1786 Either ``(body, status, headers)``, ``(body, status)``, or1787 ``(body, headers)``, where ``body`` is any of the other types1788 allowed here, ``status`` is a string or an integer, and1789 ``headers`` is a dictionary or a list of ``(key, value)``1790 tuples. If ``body`` is a :attr:`response_class` instance,1791 ``status`` overwrites the exiting value and ``headers`` are1792 extended.1747- 1793+1794 :attr:`response_class`1795 The object is returned unchanged.1750- 1796+1797 other :class:`~werkzeug.wrappers.Response` class1798 The object is coerced to :attr:`response_class`.1753- 1799+1800 :func:`callable`1801 The function is called as a WSGI application. The result is1802 used to create a response object.1803 86 unmodified lines1890 # to work.1891 if self.config['SERVER_NAME'] is not None:1892 return self.url_map.bind(1893 self.config['SERVER_NAME'],1848- script_name=self.config['APPLICATION_ROOT'] or '/',1894+ script_name=self.config['APPLICATION_ROOT'],1895 url_scheme=self.config['PREFERRED_URL_SCHEME'])1896 1897 def inject_url_defaults(self, endpoint, values):1898 """Injects the URL defaults for the given endpoint directly into33 unmodified lines1932 """Called before the request is dispatched. Calls1933 :attr:`url_value_preprocessors` registered with the app and the1934 current blueprint (if any). Then calls :attr:`before_request_funcs`1935 registered with the app and the blueprint.1890- 1936+1937 If any :meth:`before_request` handler returns a non-None value, the1938 value is handled as if it was the return value from the view, and1939 further request handling is stopped.1940 """36 unmodified lines1977 funcs = chain(funcs, reversed(self.after_request_funcs[None]))1978 for handler in funcs:1979 response = handler(response)1980 if not self.session_interface.is_null_session(ctx.session):1935- self.save_session(ctx.session, response)1981+ self.session_interface.save_session(self, ctx.session, response)1982 return response1983 1984 def do_teardown_request(self, exc=_sentinel):1985 """Called after the actual request dispatching and will76 unmodified lines2062 2063 def test_request_context(self, *args, **kwargs):2064 """Creates a WSGI environment from the given values (see2065 :class:`werkzeug.test.EnvironBuilder` for more information, this2020- function accepts the same arguments).2066+ function accepts the same arguments plus two additional).2067+2068+ Additional arguments (only if ``base_url`` is not specified):2069+2070+ :param subdomain: subdomain to use for route matching2071+ :param url_scheme: scheme for the request, default2072+ ``PREFERRED_URL_SCHEME`` or ``http``.2073 """2074+2075 from flask.testing import make_test_environ_builder2076+2077 builder = make_test_environ_builder(self, *args, **kwargs)2078+2079 try:2080 return self.request_context(builder.get_environ())2081 finally:2082 builder.close()53 unmodified linesmodified:flask/cli.py+71 added-22 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import ast13+import inspect14 import os15+import re16 import sys17 import traceback18 from functools import update_wrapper19 from operator import attrgetter37 unmodified lines57 ' Use "FLASK_APP={module}:name" to specify the correct'58 ' one.'.format(module=module.__name__)59 )60 58- # Search for app factory callables.61+ # Search for app factory functions.62 for attr_name in ('create_app', 'make_app'):63 app_factory = getattr(module, attr_name, None)64 62- if callable(app_factory):65+ if inspect.isfunction(app_factory):66 try:67 app = call_factory(app_factory, script_info)68 if isinstance(app, Flask):69 return app70 except TypeError:71 raise NoAppException(69- 'Auto-detected "{callable}()" in module "{module}", but '72+ 'Auto-detected "{function}()" in module "{module}", but '73 'could not call it without specifying arguments.'.format(71- callable=attr_name, module=module.__name__74+ function=attr_name, module=module.__name__75 )76 )77 78 raise NoAppException(2 unmodified lines81 'middleware.'.format(module=module.__name__)82 )83 84 82-def call_factory(func, script_info):83- """Checks if the given app factory function has an argument named 84- ``script_info`` or just a single argument and calls the function passing 85- ``script_info`` if so. Otherwise, calls the function without any arguments86- and returns the result.85+def call_factory(app_factory, script_info, arguments=()):86+ """Takes an app factory, a ``script_info` object and optionally a tuple87+ of arguments. Checks for the existence of a script_info argument and calls88+ the app_factory depending on that and the arguments provided.89 """88- arguments = getargspec(func).args89- if 'script_info' in arguments:90- return func(script_info=script_info)91- elif len(arguments) == 1:92- return func(script_info)93- return func()90+ args_spec = getargspec(app_factory)91+ arg_names = args_spec.args92+ arg_defaults = args_spec.defaults93 94+ if 'script_info' in arg_names:95+ return app_factory(*arguments, script_info=script_info)96+ elif arguments:97+ return app_factory(*arguments)98+ elif not arguments and len(arg_names) == 1 and arg_defaults is None:99+ return app_factory(script_info)100+ return app_factory()101 102+103+def find_app_by_string(string, script_info, module):104+ """Checks if the given string is a variable name or a function. If it is105+ a function, it checks for specified arguments and whether it takes106+ a ``script_info`` argument and calls the function with the appropriate107+ arguments."""108+ from . import Flask109+ function_regex = r'^(?P<name>\w+)(?:\((?P<args>.*)\))?$'110+ match = re.match(function_regex, string)111+ if match:112+ name, args = match.groups()113+ try:114+ if args is not None:115+ args = args.rstrip(' ,')116+ if args:117+ args = ast.literal_eval(118+ "({args}, )".format(args=args))119+ else:120+ args = ()121+ app_factory = getattr(module, name, None)122+ app = call_factory(app_factory, script_info, args)123+ else:124+ attr = getattr(module, name, None)125+ if inspect.isfunction(attr):126+ app = call_factory(attr, script_info)127+ else:128+ app = attr129+130+ if isinstance(app, Flask):131+ return app132+ else:133+ raise RuntimeError('Failed to find application in module '134+ '"{name}"'.format(name=module))135+ except TypeError as e:136+ new_error = NoAppException(137+ '{e}\nThe app factory "{factory}" in module "{module}" could'138+ ' not be called with the specified arguments (and a'139+ ' script_info argument automatically added if applicable).'140+ ' Did you make sure to use the right number of arguments as'141+ ' well as not using keyword arguments or'142+ ' non-literals?'.format(e=e, factory=string, module=module))143+ reraise(NoAppException, new_error, sys.exc_info()[2])144+ else:145+ raise NoAppException(146+ 'The provided string "{string}" is not a valid variable name'147+ 'or function expression.'.format(string=string))148+149+150 def prepare_exec_for_file(filename):151 """Given a filename this will try to calculate the python path, add it152 to the search path and return the actual module name that is expected.153 """47 unmodified lines201 'ensure the extension is .py' % module)202 203 mod = sys.modules[module]204 if app_obj is None:151- app = find_best_app(script_info, mod)205+ return find_best_app(script_info, mod)206 else:153- app = getattr(mod, app_obj, None)154- if app is None:155- raise RuntimeError('Failed to find application in module "%s"'156- % module)207+ return find_app_by_string(app_obj, script_info, mod)208 158- return app209 160-210 def find_default_import_path():211 app = os.environ.get('FLASK_APP')212 if app is None:213 return457 unmodified linesmodified:flask/ctx.py+4 added-2 removed
327 unmodified lines328 # Open the session at the moment that the request context is329 # available. This allows a custom open_session method to use the330 # request context (e.g. code that access database information331 # stored on `g` instead of the appcontext).332- self.session = self.app.open_session(self.request)332+ session_interface = self.app.session_interface333+ self.session = session_interface.open_session(self.app, self.request)334+335 if self.session is None:334- self.session = self.app.make_null_session()336+ self.session = session_interface.make_null_session(self.app)337 338 def pop(self, exc=_sentinel):339 """Pops the request context and unbinds it by doing that. This will340 also trigger the execution of functions registered by the72 unmodified linesmodified:flask/helpers.py-14 removed
1002 unmodified lines1003 else:1004 return True1005 1006 return False1007-1008-1009-def patch_vary_header(response, value):1010- """Add a value to the ``Vary`` header if it is not already present."""1011-1012- header = response.headers.get('Vary', '')1013- headers = [h for h in (h.strip() for h in header.split(',')) if h]1014- lower_value = value.lower()1015-1016- if not any(h.lower() == lower_value for h in headers):1017- headers.append(value)1018-1019- updated_header = ', '.join(headers)1020- response.headers['Vary'] = updated_headermodified:flask/sessions.py+3 added-4 removed
16 unmodified lines17 from itsdangerous import BadSignature, URLSafeTimedSerializer18 from werkzeug.datastructures import CallbackDict19 from werkzeug.http import http_date, parse_date20 21-from flask.helpers import patch_vary_header21 from . import Markup, json22 from ._compat import iteritems, text_type23 from .helpers import is_ip, total_seconds24 320 unmodified lines345 default implementation uses the value from the ``SESSION_COOKIE_PATH``346 config var if it's set, and falls back to ``APPLICATION_ROOT`` or347 uses ``/`` if it's ``None``.348 """350- return app.config['SESSION_COOKIE_PATH'] or \351- app.config['APPLICATION_ROOT'] or '/'349+ return app.config['SESSION_COOKIE_PATH'] \350+ or app.config['APPLICATION_ROOT']351 352 def get_cookie_httponly(self, app):353 """Returns True if the session cookie should be httponly. This354 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``109 unmodified lines464 return465 466 # Add a "Vary: Cookie" header if the session was accessed at all.467 if session.accessed:469- patch_vary_header(response, 'Cookie')468+ response.vary.add('Cookie')469 470 if not self.should_set_cookie(app, session):471 return472 13 unmodified linesmodified:flask/testing.py+32 added-13 removed
19 unmodified lines20 except ImportError:21 from urlparse import urlsplit as url_parse22 23 24-def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):24+def make_test_environ_builder(25+ app, path='/', base_url=None, subdomain=None, url_scheme=None,26+ *args, **kwargs27+):28 """Creates a new test builder with some application defaults thrown in."""26- http_host = app.config.get('SERVER_NAME')27- app_root = app.config.get('APPLICATION_ROOT')29+30+ assert (31+ not (base_url or subdomain or url_scheme)32+ or (base_url is not None) != bool(subdomain or url_scheme)33+ ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'34+35 if base_url is None:36+ http_host = app.config.get('SERVER_NAME') or 'localhost'37+ app_root = app.config['APPLICATION_ROOT']38+39+ if subdomain:40+ http_host = '{0}.{1}'.format(subdomain, http_host)41+42+ if url_scheme is None:43+ url_scheme = app.config['PREFERRED_URL_SCHEME']44+45 url = url_parse(path)30- base_url = 'http://%s/' % (url.netloc or http_host or 'localhost')31- if app_root:32- base_url += app_root.lstrip('/')33- if url.netloc:34- path = url.path35- if url.query:36- path += '?' + url.query46+ base_url = '{0}://{1}/{2}'.format(47+ url_scheme, url.netloc or http_host, app_root.lstrip('/')48+ )49+ path = url.path50+51+ if url.query:52+ sep = b'?' if isinstance(url.query, bytes) else '?'53+ path += sep + url.query54+55 return EnvironBuilder(path, base_url, *args, **kwargs)56 57 58 class FlaskClient(Client):45 unmodified lines104 environ_overrides = kwargs.setdefault('environ_overrides', {})105 self.cookie_jar.inject_wsgi(environ_overrides)106 outer_reqctx = _request_ctx_stack.top107 with app.test_request_context(*args, **kwargs) as c:90- sess = app.open_session(c.request)108+ session_interface = app.session_interface109+ sess = session_interface.open_session(app, c.request)110 if sess is None:111 raise RuntimeError('Session backend did not open a session. '112 'Check the configuration')113 10 unmodified lines124 finally:125 _request_ctx_stack.pop()126 127 resp = app.response_class()109- if not app.session_interface.is_null_session(sess):110- app.save_session(sess, resp)128+ if not session_interface.is_null_session(sess):129+ session_interface.save_session(app, sess, resp)130 headers = resp.get_wsgi_headers(c.request.environ)131 self.cookie_jar.extract_wsgi(c.request.environ, headers)132 133 def open(self, *args, **kwargs):29 unmodified linesadded:tests/test_apps/cliapp/factory.py+15 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+6+def create_app():7+ return Flask('create_app')8+9+10+def create_app2(foo, bar):11+ return Flask("_".join(['create_app2', foo, bar]))12+13+14+def create_app3(foo, bar, script_info):15+ return Flask("_".join(['create_app3', foo, bar]))modified:tests/test_basic.py+24 added-11 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest13-12+import pickle13 import re15-import uuid14 import time17-import flask18-import pickle15+import uuid16 from datetime import datetime17 from threading import Thread21-from flask._compat import text_type22-from werkzeug.exceptions import BadRequest, NotFound, Forbidden18+19+import pytest20+import werkzeug.serving21+from werkzeug.exceptions import BadRequest, Forbidden, NotFound22 from werkzeug.http import parse_date23 from werkzeug.routing import BuildError25-import werkzeug.serving24 25+import flask26+from flask._compat import text_type27 28+29 def test_options_work(app, client):30 @app.route('/', methods=['GET', 'POST'])31 def index():32 return 'Hello World'496 unmodified lines529 530 @app.route('/vary-cookie-header-set')531 def vary_cookie_header_set():532 response = flask.Response()532- response.headers['Vary'] = 'Cookie'533+ response.vary.add('Cookie')534 flask.session['test'] = 'test'535 return response536 537 @app.route('/vary-header-set')538 def vary_header_set():539 response = flask.Response()539- response.headers['Vary'] = 'Accept-Encoding, Accept-Language'540+ response.vary.update(('Accept-Encoding', 'Accept-Language'))541 flask.session['test'] = 'test'542 return response543 544 @app.route('/no-vary-header')330 unmodified lines875 assert rv.status_code == 403876 assert b'forbidden' == rv.data877 878 879+def test_error_handler_unknown_code(app):880+ with pytest.raises(KeyError) as exc_info:881+ app.register_error_handler(999, lambda e: ('999', 999))882+883+ assert 'Use a subclass' in exc_info.value.args[0]884+885+886 def test_error_handling_processing(app, client):887 app.config['LOGGER_HANDLER_POLICY'] = 'never'888 app.testing = False889 97 unmodified lines987 @app.route('/fail')988 def fail():989 flask.request.form['missing_key']990 991+ rv = client.get('/fail')983- assert client.get('/fail').status_code == 400992+ assert rv.status_code == 400993+ assert b'missing_key' not in rv.data994 995 app.config['TRAP_BAD_REQUEST_ERRORS'] = True996+997 with pytest.raises(KeyError) as e:998 client.get("/fail")999+1000 assert e.errisinstance(BadRequest)1001+ assert 'missing_key' in e.value.description1002 1003 1004 def test_trapping_of_all_http_exceptions(app, client):1005 app.config['TRAP_HTTP_EXCEPTIONS'] = True830 unmodified linesmodified:tests/test_cli.py+30 added-8 removed
148 unmodified lines149 """Test of locate_app."""150 script_info = ScriptInfo()151 assert locate_app(script_info, "cliapp.app").name == "testapp"152 assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153+ assert locate_app(script_info, "cliapp.factory").name == "create_app"154+ assert locate_app(155+ script_info, "cliapp.factory").name == "create_app"156+ assert locate_app(157+ script_info, "cliapp.factory:create_app").name == "create_app"158+ assert locate_app(159+ script_info, "cliapp.factory:create_app()").name == "create_app"160+ assert locate_app(161+ script_info, "cliapp.factory:create_app2('foo', 'bar')"162+ ).name == "create_app2_foo_bar"163+ assert locate_app(164+ script_info, "cliapp.factory:create_app2('foo', 'bar', )"165+ ).name == "create_app2_foo_bar"166+ assert locate_app(167+ script_info, "cliapp.factory:create_app3('baz', 'qux')"168+ ).name == "create_app3_baz_qux"169 assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"154- pytest.raises(NoAppException, locate_app,155- script_info, "notanpp.py")156- pytest.raises(NoAppException, locate_app,157- script_info, "cliapp/app")158- pytest.raises(RuntimeError, locate_app,159- script_info, "cliapp.app:notanapp")160- pytest.raises(NoAppException, locate_app,161- script_info, "cliapp.importerrorapp")170+ pytest.raises(171+ NoAppException, locate_app, script_info, "notanpp.py")172+ pytest.raises(173+ NoAppException, locate_app, script_info, "cliapp/app")174+ pytest.raises(175+ RuntimeError, locate_app, script_info, "cliapp.app:notanapp")176+ pytest.raises(177+ NoAppException, locate_app,178+ script_info, "cliapp.factory:create_app2('foo')")179+ pytest.raises(180+ NoAppException, locate_app,181+ script_info, "cliapp.factory:create_app ()")182+ pytest.raises(183+ NoAppException, locate_app, script_info, "cliapp.importerrorapp")184 185 186 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):187 """Test of find_default_import_path."""181 unmodified linesmodified:tests/test_helpers.py+2 added
42 unmodified lines43 flask.request.get_json(silent=False, cache=False)44 45 def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):46 app.config['DEBUG'] = True47+ app.config['TRAP_BAD_REQUEST_ERRORS'] = False48 49 @app.route('/json', methods=['POST'])50 def post_json():51 flask.request.get_json()4 unmodified lines56 assert b'Failed to decode JSON object' in rv.data57 58 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):59 app.config['DEBUG'] = False60+ app.config['TRAP_BAD_REQUEST_ERRORS'] = False61 62 @app.route('/json', methods=['POST'])63 def post_json():64 flask.request.get_json()868 unmodified linesmodified:tests/test_testing.py+32 added
71 unmodified lines72 assert rv.data == b'0.0.0.1'73 assert flask.g.user_agent == 'Bar'74 75 76+def test_specify_url_scheme(app, client):77+ @app.route('/')78+ def index():79+ return flask.request.url80+81+ ctx = app.test_request_context(url_scheme='https')82+ assert ctx.request.url == 'https://localhost/'83+84+ rv = client.get('/', url_scheme='https')85+ assert rv.data == b'https://localhost/'86+87+88+def test_blueprint_with_subdomain(app, client):89+ app.config['SERVER_NAME'] = 'example.com:1234'90+ app.config['APPLICATION_ROOT'] = '/foo'91+92+ bp = flask.Blueprint('company', __name__, subdomain='xxx')93+94+ @bp.route('/')95+ def index():96+ return flask.request.url97+98+ app.register_blueprint(bp)99+100+ ctx = app.test_request_context('/', subdomain='xxx')101+ assert ctx.request.url == 'http://xxx.example.com:1234/foo/'102+ assert ctx.request.blueprint == bp.name103+104+ rv = client.get('/', subdomain='xxx')105+ assert rv.data == b'http://xxx.example.com:1234/foo/'106+107+108 def test_redirect_keep_session(app, client, app_ctx):109 app.secret_key = 'testing'110 111 @app.route('/', methods=['GET', 'POST'])186 unmodified linesdeleted:.gitmodules-3 removed
1-[submodule "docs/_themes"]2- path = docs/_themes3- url = https://github.com/mitsuhiko/flask-sphinx-themes.gitmodified:.travis.yml+9 added-33 removed
2 unmodified lines3 4 matrix:5 include:6 - python: 3.67- env: TOXENV=py-release,codecov7+ env: TOXENV=py,codecov8 - python: 3.59- env: TOXENV=py-release,codecov9+ env: TOXENV=py,codecov10 - python: 3.411- env: TOXENV=py-release,codecov11+ env: TOXENV=py,codecov12 - python: 3.313- env: TOXENV=py-release,codecov13+ env: TOXENV=py,codecov14 - python: 2.715- env: TOXENV=py-release,codecov15+ env: TOXENV=py,codecov16 - python: 2.617- env: TOXENV=py-release,codecov17+ env: TOXENV=py,codecov18 - python: pypy19- env: TOXENV=py-release,codecov19+ env: TOXENV=py,codecov20 - python: nightly21- env: TOXENV=py-release21+ env: TOXENV=py22 - python: 3.623 env: TOXENV=docs-html24 - python: 3.625- env: TOXENV=py-release-simplejson,codecov26- - python: 2.727- env: TOXENV=py-release-simplejson,codecov28- - python: pypy29- env: TOXENV=py-release-simplejson,codecov30- - python: 3.631- env: TOXENV=py-devel,codecov32- - python: 3.333- env: TOXENV=py-devel,codecov34- - python: 2.735- env: TOXENV=py-devel,codecov36- - python: 2.637- env: TOXENV=py-devel,codecov38- - python: pypy39- env: TOXENV=py-devel,codecov40- - python: 3.641- env: TOXENV=py-lowest,codecov42- - python: 3.343- env: TOXENV=py-lowest,codecov44- - python: 2.745- env: TOXENV=py-lowest,codecov46- - python: 2.647- env: TOXENV=py-lowest,codecov48- - python: pypy49- env: TOXENV=py-lowest,codecov25+ env: TOXENV=py-simplejson,codecov26 27 install:28 - pip install tox29 15 unmodified linesmodified:CHANGES+35 added-9 removed
6 unmodified lines7 ------------8 9 Major release, unreleased10 11+- Minimum Werkzeug version bumped to 0.9, but please use the latest version.12+- Minimum Click version bumped to 4, but please use the latest version.11-- Make `app.run()` into a noop if a Flask application is run from the12- development server on the command line. This avoids some behavior that13+- Make ``app.run()`` into a noop if a Flask application is run from the14+ development server on the command line. This avoids some behavior that15 was confusing to debug for newcomers.14-- Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify()15- method returns compressed response by default, and pretty response in16- debug mode.17-- Change Flask.__init__ to accept two new keyword arguments, ``host_matching``18- and ``static_host``. This enables ``host_matching`` to be set properly by the19- time the constructor adds the static route, and enables the static route to20- be properly associated with the required host. (``#1559``)16+- Change default configuration ``JSONIFY_PRETTYPRINT_REGULAR=False``.17+ ``jsonify()`` method returns compressed response by default, and pretty18+ response in debug mode. (`#2193`_)19+- Change ``Flask.__init__`` to accept two new keyword arguments,20+ ``host_matching`` and ``static_host``. This enables ``host_matching`` to be21+ set properly by the time the constructor adds the static route, and enables22+ the static route to be properly associated with the required host.23+ (``#1559``)24 - ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)25 - Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.26 (`#2017`_)27 - Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable20 unmodified lines48 - Factory functions are not required to take a ``script_info`` parameter to49 work with the ``flask`` command. If they take a single parameter or a50 parameter named ``script_info``, the ``ScriptInfo`` object will be passed.51 (`#2319`_)52+- FLASK_APP=myproject.app:create_app('dev') support.53+- ``FLASK_APP`` can be set to an app factory, with arguments if needed, for54+ example ``FLASK_APP=myproject.app:create_app('dev')``. (`#2326`_)55+- ``View.provide_automatic_options = True`` is set on the view function from56+ ``View.as_view``, to be detected in ``app.add_url_rule``. (`#2316`_)57+- Error handling will try handlers registered for ``blueprint, code``,58+ ``app, code``, ``blueprint, exception``, ``app, exception``. (`#2314`_)59+- ``Cookie`` is added to the response's ``Vary`` header if the session is60+ accessed at all during the request (and it wasn't deleted). (`#2288`_)61+- ``app.test_request_context()`` take ``subdomain`` and ``url_scheme``62+ parameters for use when building base URL. (`#1621`_)63+- Set ``APPLICATION_ROOT = '/'`` by default. This was already the implicit64+ default when it was set to ``None``.65+- ``TRAP_BAD_REQUEST_ERRORS`` is enabled by default in debug mode.66+ ``BadRequestKeyError`` has a message with the bad key in debug mode instead67+ of the generic bad request message. (`#2348`_)68 69 .. _#1489: https://github.com/pallets/flask/pull/148970+.. _#1621: https://github.com/pallets/flask/pull/162171 .. _#1898: https://github.com/pallets/flask/pull/189872 .. _#1936: https://github.com/pallets/flask/pull/193673 .. _#2017: https://github.com/pallets/flask/pull/201774+.. _#2193: https://github.com/pallets/flask/pull/219375 .. _#2223: https://github.com/pallets/flask/pull/222376 .. _#2254: https://github.com/pallets/flask/pull/225477 .. _#2256: https://github.com/pallets/flask/pull/225678 .. _#2259: https://github.com/pallets/flask/pull/225979 .. _#2282: https://github.com/pallets/flask/pull/228280+.. _#2288: https://github.com/pallets/flask/pull/228881 .. _#2297: https://github.com/pallets/flask/pull/229782+.. _#2314: https://github.com/pallets/flask/pull/231483+.. _#2316: https://github.com/pallets/flask/pull/231684 .. _#2319: https://github.com/pallets/flask/pull/231985+.. _#2326: https://github.com/pallets/flask/pull/232686+.. _#2348: https://github.com/pallets/flask/pull/234887 88 Version 0.12.289 --------------90 617 unmodified linesmodified:CONTRIBUTING.rst+93 added-92 removed
1-==========================1 How to contribute to Flask2 ==========================3 5-Thanks for considering contributing to Flask.4+Thank you for considering contributing to Flask!5 6 Support questions8-=================7+-----------------8 10-Please, don't use the issue tracker for this. Check whether the ``#pocoo`` IRC11-channel on Freenode can help with your issue. If your problem is not strictly12-Werkzeug or Flask specific, ``#python`` is generally more active.13-`Stack Overflow <https://stackoverflow.com/>`_ is also worth considering.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.14+* The mailing list flask@python.org for long term discussion or larger issues.15+* Ask on `Stack Overflow`_. Search with Google first using:16+ ``site:stackoverflow.com flask {search term, exception message, etc.}``17+18+.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked19+20 Reporting issues16-================21+----------------22 18-- Under which versions of Python does this happen? This is even more important19- if your issue is encoding related.23+- Describe what you expected to happen.24+- If possible, include a `minimal, complete, and verifiable example`_ to help25+ us identify the issue. This also helps check that the issue is not with your26+ own code.27+- Describe what actually happened. Include the full traceback if there was an28+ exception.29+- List your Python, Flask, and Werkzeug versions. If possible, check if this30+ issue is already fixed in the repository.31 21-- Under which versions of Werkzeug does this happen? Check if this issue is22- fixed in the repository.32+.. _minimal, complete, and verifiable example: https://stackoverflow.com/help/mcve33 34 Submitting patches25-==================35+------------------36 37 - Include tests if your patch is supposed to solve a bug, and explain38 clearly under which circumstances the bug happens. Make sure the test fails39 without your patch.40+- Try to follow `PEP8`_, but you may ignore the line length limit if following41+ it would make the code uglier.42 31-- Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32- may ignore the line-length-limit if following it would make the code uglier.33-43 First time setup35-----------------44+~~~~~~~~~~~~~~~~45 46 - Download and install the `latest version of git`_.38-- Configure git with your `username`_ and `email`_.47+- Configure git with your `username`_ and `email`_::48+49+ git config --global user.name 'your name'50+ git config --global user.email 'your email'51+52 - Make sure you have a `GitHub account`_.53 - Fork Flask to your GitHub account by clicking the `Fork`_ button.41-- `Clone`_ your GitHub fork locally.42-- Add the main repository as a remote to update later.43- ``git remote add pallets https://github.com/pallets/flask``54+- `Clone`_ your GitHub fork locally::55 56+ git clone https://github.com/{username}/flask57+ cd flask58+59+- Add the main repository as a remote to update later::60+61+ git remote add pallets https://github.com/pallets/flask62+ git fetch pallets63+64+- Create a virtualenv::65+66+ python3 -m venv env67+ . env/bin/activate68+ # or "env\Scripts\activate" on Windows69+70+- Install Flask in editable mode with development dependencies::71+72+ pip install -e ".[dev]"73+74 .. _GitHub account: https://github.com/join75 .. _latest version of git: https://git-scm.com/downloads76 .. _username: https://help.github.com/articles/setting-your-username-in-git/77 .. _email: https://help.github.com/articles/setting-your-email-in-git/78 .. _Fork: https://github.com/pallets/flask/pull/2305#fork-destination-box79 .. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork80 81 Start coding53-------------82+~~~~~~~~~~~~83 84 - Create a branch to identify the issue you would like to work on (e.g.85 ``2287-dry-test-suite``)86 - Using your favorite editor, make your changes, `committing as you go`_.9 unmodified lines96 .. _create a pull request: https://help.github.com/articles/creating-a-pull-request/97 98 .. _contributing-testsuite:99 71-Running the testsuite72----------------------100+Running the tests101+~~~~~~~~~~~~~~~~~102 74-You probably want to set up a `virtualenv75-<https://virtualenv.readthedocs.io/en/latest/index.html>`_.103+Run the basic test suite with::104 77-The minimal requirement for running the testsuite is ``pytest``. You can78-install it with::105+ pytest106 80- pip install pytest107+This only runs the tests for the current environment. Whether this is relevant108+depends on which part of Flask you're working on. Travis-CI will run the full109+suite when you submit your pull request.110 82-Clone this repository::111+The full test suite takes a long time to run because it tests multiple112+combinations of Python and dependencies. You need to have Python 2.6, 2.7, 3.3,113+3.4, 3.5 3.6, and PyPy 2.7 installed to run all of the environments. Then run::114 84- git clone https://github.com/pallets/flask.git115+ tox116 86-Install Flask as an editable package using the current source::87-88- cd flask89- pip install --editable .90-91-Running the testsuite92----------------------93-94-The minimal requirement for running the testsuite is ``pytest``. You can95-install it with::96-97- pip install pytest98-99-Then you can run the testsuite with::100-101- pytest tests/102-103-**Shortcut**: ``make test`` will ensure ``pytest`` is installed, and run it.104-105-With only pytest installed, a large part of the testsuite will get skipped106-though. Whether this is relevant depends on which part of Flask you're working107-on. Travis is set up to run the full testsuite when you submit your pull108-request anyways.109-110-If you really want to test everything, you will have to install ``tox`` instead111-of ``pytest``. You can install it with::112-113- pip install tox114-115-The ``tox`` command will then run all tests against multiple combinations116-Python versions and dependency versions.117-118-**Shortcut**: ``make tox-test`` will ensure ``tox`` is installed, and run it.119-117 Running test coverage121----------------------122-Generating a report of lines that do not have unit test coverage can indicate where123-to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``124-plugin. This assumes you have already run the testsuite (see previous section)::118+~~~~~~~~~~~~~~~~~~~~~119 126- pip install pytest-cov120+Generating a report of lines that do not have test coverage can indicate121+where to start contributing. Run ``pytest`` using ``coverage`` and generate a122+report on the terminal and as an interactive HTML document::123 128-After this has been installed, you can output a report to the command line using this command::124+ coverage run -m pytest125+ coverage report126+ coverage html127+ # then open htmlcov/index.html128 130- pytest --cov=flask tests/129+Read more about `coverage <https://coverage.readthedocs.io>`_.130 132-Generate a HTML report can be done using this command::131+Running the full test suite with ``tox`` will combine the coverage reports132+from all runs.133 134- pytest --cov-report html --cov=flask tests/134+``make`` targets135+~~~~~~~~~~~~~~~~136 136-Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io137+Flask provides a ``Makefile`` with various shortcuts. They will ensure that138+all dependencies are installed.139 138-**Shortcut**: ``make cov`` will ensure ``pytest-cov`` is installed, run it, display the results, *and* save the HTML report.140+- ``make test`` runs the basic test suite with ``pytest``141+- ``make cov`` runs the basic test suite with ``coverage``142+- ``make test-all`` runs the full test suite with ``tox``143+- ``make docs`` builds the HTML documentation144 145+Caution: zero-padded file modes146+-------------------------------147 141-Caution142-=======143-pushing144--------145-This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than github. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like Gitlab, you can turn off repository checks in the admin panel.148+This repository contains several zero-padded file modes that may cause issues149+when pushing this repository to git hosts other than GitHub. Fixing this is150+destructive to the commit history, so we suggest ignoring these warnings. If it151+fails to push and you're using a self-hosted git service like GitLab, you can152+turn off repository checks in the admin panel.153 154+These files can also cause issues while cloning. If you have ::155 148-cloning149--------150-The zero-padded file modes files above can cause issues while cloning, too. If you have151-152-::153-156 [fetch]157 fsckobjects = true158 157-or159+or ::160 159-::160-161 [receive]162 fsckObjects = true163 164-165-set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.164+set in your git configuration file, cloning this repository will fail. The only165+solution is to set both of the above settings to false while cloning, and then166+setting them back to true after the cloning is finished.modified:Makefile+22 added-14 removed
1-.PHONY: clean-pyc ext-test test tox-test test-with-mem upload-docs docs audit1+.PHONY: all install-dev test coverage cov test-all tox docs audit release clean-pyc upload-docs ebook2 3-all: clean-pyc test3+all: test4 5-test:6- pip install -r test-requirements.txt7- tox -e py-release5+install-dev:6+ pip install -q -e .[dev]7 9-cov:10- pip install -r test-requirements.txt -q11- FLASK_DEBUG= py.test --cov-report term --cov-report html --cov=flask --cov=examples tests examples8+test: clean-pyc install-dev9+ pytest10 11+coverage: clean-pyc install-dev12+ pip install -q -e .[test]13+ coverage run -m pytest14+ coverage report15+ coverage html16+17+cov: coverage18+19+test-all: install-dev20+ tox21+22+tox: test-all23+24+docs: clean-pyc install-dev25+ $(MAKE) -C docs html26+27 audit:28 python setup.py audit29 30 release:31 python scripts/make-release.py32 19-ext-test:20- python tests/flaskext_test.py --browse21-33 clean-pyc:34 find . -name '*.pyc' -exec rm -f {} +35 find . -name '*.pyo' -exec rm -f {} +36 find . -name '*~' -exec rm -f {} +13 unmodified lines50 @echo 'Command `ebook-covert` is provided by calibre package.'51 @echo 'Requires X-forwarding for Qt features used in conversion (ssh -X).'52 @echo 'Do not mind "Invalid value for ..." CSS errors if .mobi renders.'53 ssh -X pocoo.org ebook-convert /var/www/flask.pocoo.org/docs/flask-docs.epub /var/www/flask.pocoo.org/docs/flask-docs.mobi --cover http://flask.pocoo.org/docs/_images/logo-full.png --authors 'Armin Ronacher'43-44-docs:45- $(MAKE) -C docs htmlmodified:setup.py+12 added-2 removed
46 unmodified lines47 import re48 import ast49 from setuptools import setup50 51-51 _version_re = re.compile(r'__version__\s+=\s+(.*)')52 53 with open('flask/__init__.py', 'rb') as f:54 version = str(ast.literal_eval(_version_re.search(55 f.read().decode('utf-8')).group(1)))56 58-57 setup(58 name='Flask',59 version=version,60 url='https://github.com/pallets/flask/',12 unmodified lines73 'Jinja2>=2.4',74 'itsdangerous>=0.21',75 'click>=4.0',76 ],77+ extras_require={78+ 'dev': [79+ 'blinker',80+ 'greenlet',81+ 'pytest>=3',82+ 'coverage',83+ 'tox',84+ 'sphinx',85+ 'sphinxcontrib-log-cabinet'86+ ],87+ },88 classifiers=[89 'Development Status :: 4 - Beta',90 'Environment :: Web Environment',91 'Intended Audience :: Developers',6 unmodified lines98 'Programming Language :: Python :: 3',99 'Programming Language :: Python :: 3.3',100 'Programming Language :: Python :: 3.4',101 'Programming Language :: Python :: 3.5',102+ 'Programming Language :: Python :: 3.6',103 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',104 'Topic :: Software Development :: Libraries :: Python Modules'105 ],106 entry_points='''4 unmodified linesmodified:tox.ini+11 added-6 removed
1 [tox]2 envlist =3- py{36,35,34,33,27,26,py}-release4- py{36,27,py}-release-simplejson3+ py{36,35,34,33,27,26,py}4+ py{36,27,py}-simplejson5 py{36,33,27,26,py}-devel6 py{36,33,27,26,py}-lowest7 docs-html8 coverage-report25 unmodified lines34 pip install -e examples/minitwit -q35 pip install -e examples/patterns/largerapp -q36 37 # pytest-cov doesn't seem to play nice with -p38- coverage run -p -m pytest38+ coverage run -p -m pytest tests examples39 40 [testenv:docs-html]41-deps =42- sphinx43- flask-sphinx-themes41+deps = sphinx42 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html43 44 [testenv:docs-linkcheck]45 deps = sphinx14 unmodified lines60 commands =61 coverage combine62 coverage report63 codecov64+65+[testenv:detox]66+skip_install = true67+deps = detox68+commands =69+ detox -e py{36,35,34,33,27,26,py},py{36,27,py}-simplejson,py{36,33,27,26,py}-devel,py{36,33,27,26,py}-lowest,docs-html70+ tox -e coverage-report