Skip to content
Myr

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

43 files+1169 added−731 removed

modified:.github/ISSUE_TEMPLATE.rst+33 added-2 removed
1The issue tracker is a tool to address bugs.2Please 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.2Please use the #pocoo IRC channel on freenode or Stack Overflow for general3questions about using Jinja or issues not related to Jinja.**45If you'd like to report a bug in Flask, fill out the template below. Provide6any any extra information that may be useful / related to your problem.7Ideally, create an [MCVE](http://stackoverflow.com/help/mcve), which helps us8understand the problem and helps check that it is not caused by something in9your code.1011---1213### Expected Behavior1415Tell us what should happen.1617```python18Paste a minimal example that causes the problem.19```2021### Actual Behavior2223Tell us what happens instead.2425```pytb26Paste the full traceback if there was an exception.27```2829### Environment3031* Python version:32* Flask version:33* Werkzeug version:
added:.github/PULL_REQUEST_TEMPLATE.rst+16 added
1Describe what this patch does to fix the issue.23Link to any relevant issues or pull requests.45<!--6Commit checklist:78* 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 code1314Tests, coverage, and docs will be run automatically when you submit the pull15request, 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 lines
4=======================56.. versionadded:: 0.978One of the design ideas behind Flask is that there are two different9“states” in which code is executed. The application setup state in which10the application implicitly is on the module level. It starts when the11:class:`Flask` object is instantiated, and it implicitly ends when the12first request comes in. While the application is in this state a few13assumptions are true:8One of the design ideas behind Flask is that there are at least two9different “states” in which code is executed:1015- 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.111. The application setup state, in which the application implicitly is12on the module level.1321In 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:1723- 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.2327There is a third state which is sitting in between a little bit.28Sometimes you are dealing with an application in a way that is similar to29how you interact with applications during request handling; just that there30is no request active. Consider, for instance, that you're sitting in an31interactive Python shell and interacting with the application, or a32command line application.242. In contrast, in the request handling state, a couple of other rules25exist:2627 - 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.30313. There is also a third state somewhere in between 'module-level' and32'request-handling':3334 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.3940The application context is what powers the :data:`~flask.current_app`41context local.4243Purpose of the Application Context
101 unmodified lines
modified:docs/conf.py+4 added-17 removed
20 unmodified lines
2122# 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.25sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))25sys.path.append(os.path.dirname(__file__))2627# -- General configuration -----------------------------------------------------28
90 unmodified lines
119# documentation.120# html_theme_options = {}121122# Add any paths that contain custom themes here, relative to this directory.124html_theme_path = ['_themes']123# html_theme_path = ['_themes']124125# The name for this set of Sphinx documents. If None, it defaults to126# "<project> v<release> documentation".127#html_title = None
143 unmodified lines
271 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),272 'blinker': ('https://pythonhosted.org/blinker/', None)273}274276try: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 }275html_theme_options = {276 'touch_icon': 'touch-icon.png'277}283except 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)278291279# unwrap decorators280def unwrap_decorators():281 import sphinx.util.inspect as inspect282 import functools
15 unmodified lines
modified:docs/config.rst+236 added-166 removed
1 unmodified line
23Configuration Handling4======================56.. versionadded:: 0.376Applications need some kind of configuration. There are different settings7you might want to change depending on the application environment like8toggling the debug mode, setting the secret key, and other such9environment-specific things.
41 unmodified lines
51 $ export FLASK_DEBUG=152 $ flask run5354 (On Windows you need to use ``set`` instead of ``export``).57 58 ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 5556 ``app.debug`` and ``app.config['DEBUG']`` are not compatible with57   the :command:`flask` script. They only worked when using ``Flask.run()``58 method.61 5960Builtin Configuration Values61----------------------------6263The following configuration values are used internally by Flask:6467.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|65.. py:data:: DEBUG6669================================= =========================================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.70215.. admonition:: More on ``SERVER_NAME``71 **Do not enable debug mode in production.**72217 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``74222 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:: TESTING76232.. _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.8081 Default: ``False``8283.. py:data:: PROPAGATE_EXCEPTIONS8485 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.8889 Default: ``None``9091.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION9293 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.9697 Default: ``None``9899.. py:data:: TRAP_HTTP_EXCEPTIONS100101 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.104105 Default: ``False``106107.. py:data:: TRAP_BAD_REQUEST_ERRORS``108109 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.114115 Default: ``None``116117.. py:data:: SECRET_KEY118119 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::123124 python -c 'import os; print(os.urandom(32))'125126 **Do not reveal the secret key when posting questions or committing code.**127128 Default: ``None``129130.. py:data:: SESSION_COOKIE_NAME131132 The name of the session cookie. Can be changed in case you already have a133 cookie with the same name.134135 Default: ``'session'``136137.. py:data:: SESSION_COOKIE_DOMAIN138139 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.142143 Default: ``None``144145.. py:data:: SESSION_COOKIE_PATH146147 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.149150 Default: ``None``151152.. py:data:: SESSION_COOKIE_HTTPONLY153154 Browsers will not allow JavaScript access to cookies marked as "HTTP only"155 for security.156157 Default: ``True``158159.. py:data:: SESSION_COOKIE_SECURE160161 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.164165 Default: ``False``166167.. py:data:: PERMANENT_SESSION_LIFETIME168169 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``.172173 Default: ``timedelta(days=31)`` (``2678400`` seconds)174175.. py:data:: SESSION_REFRESH_EACH_REQUEST176177 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.181182 Default: ``True``183184.. py:data:: USE_X_SENDFILE185186 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.189190 Default: ``False``191192.. py:data:: SEND_FILE_MAX_AGE_DEFAULT193194 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.198199 Default: ``timedelta(hours=12)`` (``43200`` seconds)200201.. py:data:: LOGGER_NAME202203 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__``.205206 Default: ``None``207208.. py:data:: LOGGER_HANDLER_POLICY209210 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.213214 Default: ``'always'``215216.. py:data:: SERVER_NAME217218 Inform the application what host and port it is bound to. Required for219 subdomain route matching support.220221 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. ::225226 127.0.0.1 localhost.dev227228 If set, ``url_for`` can generate external URLs with only an application229 context instead of a request context.230231 Default: ``None``232233.. py:data:: APPLICATION_ROOT234235 Inform the application what path it is mounted under by the application /236 web server.237238 Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not239 set.240241 Default: ``'/'``242243.. py:data:: PREFERRED_URL_SCHEME244245 Use this scheme for generating external URLs when not in a request context.246247 Default: ``'http'``248249.. py:data:: MAX_CONTENT_LENGTH250251 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.254255 Default: ``None``256257.. py:data:: JSON_AS_ASCII258259 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.263264 Default: ``True``265266.. py:data:: JSON_SORT_KEYS267268 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.272273 Default: ``True``274275.. py:data:: JSONIFY_PRETTYPRINT_REGULAR276277 ``jsonify`` responses will be output with newlines, spaces, and indentation278 for easier reading by humans. Always enabled in debug mode.279280 Default: ``False``281282.. py:data:: JSONIFY_MIMETYPE283284 The mimetype of ``jsonify`` responses.285286 Default: ``'application/json'``287288.. py:data:: TEMPLATES_AUTO_RELOAD289290 Reload templates when they are changed. If not set, it will be enabled in291 debug mode.292293 Default: ``None``294295.. py:data:: EXPLAIN_TEMPLATE_LOADING296297 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.300301 Default: ``False``302303.. versionadded:: 0.4304 ``LOGGER_NAME``305306.. versionadded:: 0.5
238 unmodified lines
545546 # 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 lines
58 python359 upgrading60 changelog61 license62 contributing
added:docs/contributing.rst+1 added
1.. include:: ../CONTRIBUTING.rst
modified:docs/errorhandling.rst+47 added-24 removed
74 unmodified lines
7576You might want to show custom error pages to the user when an error occurs.77This can be done by registering error handlers.7879Error handlers are normal :ref:`views` but instead of being registered for80routes, they are registered for exceptions that are raised while trying to81do something else.79An error handler is a normal view function that return a response, but instead80of being registered for a route, it is registered for an exception or HTTP81status code that would is raised while trying to handle a request.8283Registering84```````````8586Register error handlers using :meth:`~flask.Flask.errorhandler` or87:meth:`~flask.Flask.register_error_handler`::86Register handlers by decorating a function with87:meth:`~flask.Flask.errorhandler`. Or use88:meth:`~flask.Flask.register_error_handler` to register the function later.89Remember to set the error code when returning the response. ::9091 @app.errorhandler(werkzeug.exceptions.BadRequest)92 def handle_bad_request(e):91 return 'bad request!'93 return 'bad request!', 4009495 # or, without the decorator93 app.register_error_handler(400, lambda e: 'bad request!')96 app.register_error_handler(400, handle_bad_request)9795Those two ways are equivalent, but the first one is more clear and leaves96you 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 codes99are interchangeable when handed to the registration methods or decorator100(``BadRequest.code == 400``).99:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable100when registering handlers. (``BadRequest.code == 400``)101102You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103or HTTP status codes but can register a handler for every exception class you104like.102Non-standard HTTP codes cannot be registered by code because they are not known103by Werkzeug. Instead, define a subclass of104:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105register and raise that exception class. ::106106.. versionchanged:: 0.11107 class InsufficientStorage(werkzeug.exceptions.HTTPException):108 code = 507109 description = 'Not enough storage space.'110108 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)112113 raise InsufficientStorage()114115Handlers can be registered for any exception class, not just116:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status117codes. Handlers can be registered for a specific class, or for all subclasses118of a parent class.119120Handling121````````122114Once an exception instance is raised, its class hierarchy is traversed,115and searched for in the exception classes for which handlers are registered.116The most specific handler is selected.123When an exception is caught by Flask while handling a request, it is first124looked up by code. If no handler is registered for the code, it is looked up125by its class hierarchy; the most specific handler is chosen. If no handler is126registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a127generic message about their code, while other exceptions are converted to a128generic 500 Internal Server Error.129118E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler130For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler131is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120the more specific :exc:`ConnectionRefusedError` handler is called on the121exception instance, and its response is shown to the user.132the more specific :exc:`ConnectionRefusedError` handler is called with the133exception instance to generate the response.134135Handlers registered on the blueprint take precedence over those registered136globally on the application, assuming a blueprint is handling the request that137raises the exception. However, the blueprint cannot handle 404 routing errors138because the 404 occurs at the routing level before the blueprint can be139determined.140141.. versionchanged:: 0.11142143 Handlers are prioritized by specificity of the exception classes they are144 registered for instead of the order they are registered in.145146Error Mails147-----------148149If the application runs in production mode (which it will do on your
268 unmodified lines
deleted:docs/flaskext.py-86 removed
1# flasky extensions. flasky pygments style based on tango style2from pygments.style import Style3from pygments.token import Keyword, Name, Comment, String, Error, \4 Number, Operator, Generic, Whitespace, Punctuation, Other, Literal567class FlaskyStyle(Style):8 background_color = "#f8f8f8"9 default_style = ""1011 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'1718 Comment: "italic #8f5902", # class: 'c'19 Comment.Preproc: "noitalic", # class: 'cp'2021 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'2829 Operator: "#582800", # class: 'o'30 Operator.Word: "bold #004461", # class: 'ow' - like keywords3132 Punctuation: "bold #000000", # class: 'p'3334 # 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 revised5657 Number: "#990000", # class: 'm'5859 Literal: "#000000", # class: 'l'60 Literal.Date: "#000000", # class: 'ld'6162 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'7475 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 lines
103vulnerabilities104<https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so105this behavior was changed and :func:`~flask.jsonify` now supports serializing106arrays.107108Security Headers109----------------110111Browsers recognize various response headers in order to control security. We112recommend reviewing each of the headers below for use in your application.113The `Flask-Talisman`_ extension can be used to manage HTTPS and the security114headers for you.115116.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman117118HTTP Strict Transport Security (HSTS)119~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~120121Tells the browser to convert all HTTP requests to HTTPS, preventing122man-in-the-middle (MITM) attacks. ::123124 response.haders['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'125126- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security127128Content Security Policy (CSP)129~~~~~~~~~~~~~~~~~~~~~~~~~~~~~130131Tell the browser where it can load various types of resource from. This header132should be used whenever possible, but requires some work to define the correct133policy for your site. A very strict policy would be::134135 response.headers['Content-Security-Policy'] = "default-src: 'self'"136137- https://csp.withgoogle.com/docs/index.html138- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy139140X-Content-Type-Options141~~~~~~~~~~~~~~~~~~~~~~142143Forces the browser to honor the response content type instead of trying to144detect it, which can be abused to generate a cross-site scripting (XSS)145attack. ::146147 response.headers['X-Content-Type-Options'] = 'nosniff'148149- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options150151X-Frame-Options152~~~~~~~~~~~~~~~153154Prevents external sites from embedding your site in an ``iframe``. This155prevents a class of attacks where clicks in the outer frame can be translated156invisibly to clicks on your page's elements. This is also known as157"clickjacking". ::158159 response.headers['X-Frame-Options'] = 'SAMEORIGIN'160161- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options162163X-XSS-Protection164~~~~~~~~~~~~~~~~165166The browser will try to prevent reflected XSS attacks by not loading the page167if the request contains something that looks like JavaScript and the response168contains the same data. ::169170 response.headers['X-XSS-Protection'] = '1; mode=block'171172- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection173174Set-Cookie options175~~~~~~~~~~~~~~~~~~176177These options can be added to a ``Set-Cookie`` header to improve their178security. Flask has configuration options to set these on the session cookie.179They can be set on other cookies too.180181- ``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.186187::188189 app.config.update(190 SESSION_COOKIE_SECURE=True,191 SESSION_COOKIE_HTTPONLY=True,192 )193194 response.set_cookie('username', 'flask', secure=True, httponly=True)195196- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies197198HTTP Public Key Pinning (HPKP)199~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~200201This tells the browser to authenticate with the server using only the specific202certificate key to prevent MITM attacks.203204.. warning::205 Be careful when enabling this, as it is very difficult to undo if you set up206 or upgrade your key incorrectly.207208- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning
added:examples/flaskr/flaskr/blueprints/__init__.py
added:examples/flaskr/flaskr/blueprints/flaskr.py+85 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from sqlite3 import dbapi2 as sqlite314from flask import Blueprint, request, session, g, redirect, url_for, abort, \15 render_template, flash, current_app161718# create our blueprint :)19bp = Blueprint('flaskr', __name__)202122def connect_db():23 """Connects to the specific database."""24 rv = sqlite3.connect(current_app.config['DATABASE'])25 rv.row_factory = sqlite3.Row26 return rv272829def 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()353637def 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_db444546@bp.route('/')47def 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)525354@bp.route('/add', methods=['POST'])55def 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'))646566@bp.route('/login', methods=['GET', 'POST'])67def 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)798081@bp.route('/logout')82def 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 lines
4<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 lines
modified: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 lines
modified: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 lines
modified:examples/flaskr/flaskr/__init__.py-1 removed
1from .flaskr import app
added:examples/flaskr/flaskr/factory.py+64 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from flask import Flask, g15from werkzeug.utils import find_modules, import_string16from flaskr.blueprints.flaskr import init_db171819def create_app(config=None):20 app = Flask('flaskr')2122 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)3132 register_blueprints(app)33 register_cli(app)34 register_teardowns(app)3536 return app373839def register_blueprints(app):40 """Register all blueprint modules4142 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 None495051def 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.')575859def 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 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from sqlite3 import dbapi2 as sqlite315from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash171819# create our little application :)20app = Flask(__name__)2122# Load default config and override config from an environment variable23app.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))30app.config.from_envvar('FLASKR_SETTINGS', silent=True)313233def connect_db():34 """Connects to the specific database."""35 rv = sqlite3.connect(app.config['DATABASE'])36 rv.row_factory = sqlite3.Row37 return rv383940def 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()464748@app.cli.command('initdb')49def initdb_command():50 """Creates the database tables."""51 init_db()52 print('Initialized the database.')535455def 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_db626364@app.teardown_appcontext65def 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()697071@app.route('/')72def 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)777879@app.route('/add', methods=['POST'])80def 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'))899091@app.route('/login', methods=['GET', 'POST'])92def 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)104105106@app.route('/logout')107def 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 lines
1112import os13import tempfile14import pytest15from flaskr import flaskr15from flaskr.factory import create_app16from flaskr.blueprints.flaskr import init_db171819@pytest.fixture19def 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'])20def app(request):2122 db_fd, temp_db_location = tempfile.mkstemp()23 config = {24 'DATABASE': temp_db_location,25 'TESTING': True,26 'DB_FD': db_fd27 }2829 app = create_app(config=config)3031 with app.app_context():32 init_db()33 yield app343536@pytest.fixture37def client(request, app):3839 client = app.test_client()4041 def teardown():42 os.close(app.config['DB_FD'])43 os.unlink(app.config['DATABASE'])44 request.addfinalizer(teardown)4546 return client474849def login(client, username, password):50 return client.post('/login', data=dict(51 username=username,52 password=password
9 unmodified lines
62 rv = client.get('/')63 assert b'No entries here so far' in rv.data646547def test_login_logout(client):66def 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.data798062def test_messages(client):81def 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 lines
modified:examples/flaskr/README+5 added-3 removed
7 unmodified lines
8 A sqlite powered thumble blog application910 ~ How do I use it?1112 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.1718 2. install the app from the root of the project directory1920 pip install --editable .2122 3. Instruct flask to use the right application2322 export FLASK_APP=flaskr24 export FLASK_APP=flaskr.factory:create_app()2526 4. initialize the database with this command:2728 flask initdb
12 unmodified lines
modified:examples/flaskr/setup.cfg+2 added-2 removed
1[tool:pytest]2test=pytest1[aliases]2test=pytest
modified:examples/flaskr/setup.py+13 added-2 removed
1from setuptools import setup1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from setuptools import setup, find_packages1314setup(15 name='flaskr',5 packages=['flaskr'],16 packages=find_packages(),17 include_package_data=True,18 install_requires=[19 'flask',20 ],
7 unmodified lines
modified:examples/minitwit/minitwit/minitwit.py+1 added-1 removed
23 unmodified lines
24DEBUG = True25SECRET_KEY = 'development key'2627# create our little application :)28app = Flask(__name__)28app = Flask('minitwit')29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)3132
224 unmodified lines
modified:examples/patterns/largerapp/yourapplication/__init__.py+2 added-2 removed
1from flask import Flask2app = Flask(__name__)2app = Flask('yourapplication')34import yourapplication.views4import yourapplication.views
modified:flask/app.py+92 added-37 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13import warnings14from datetime import timedelta15from functools import update_wrapper16from itertools import chain17from threading import Lock1819from werkzeug.datastructures import ImmutableDict, Headers20from werkzeug.exceptions import BadRequest, HTTPException, \20 InternalServerError, MethodNotAllowed, default_exceptions21 InternalServerError, MethodNotAllowed, default_exceptions, \22 BadRequestKeyError23from werkzeug.routing import BuildError, Map, RequestRedirect, Rule2425from . import cli, json26from ._compat import integer_types, reraise, string_types, text_type
281 unmodified lines
308 '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 lines
926 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`.929930 .. deprecated: 1.0931 Will be removed in 1.1. Use ``session_interface.open_session``932 instead.933934 :param request: an instance of :attr:`request_class`.935 """936937 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)942943 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`.947948 .. deprecated: 1.0949 Will be removed in 1.1. Use ``session_interface.save_session``950 instead.951952 :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 """957958 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)963964 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`.967968 .. deprecated: 1.0969 Will be removed in 1.1. Use ``session_interface.make_null_session``970 instead.971972 .. versionadded:: 0.7973 """974975 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)980981 @setupmethod982 def register_blueprint(self, blueprint, **options):
182 unmodified lines
1165 return exc_class, None11661167 @setupmethod1168 def errorhandler(self, code_or_exception):1169 """Register a function to handle errors by code or exception class.11701140 """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::11731174 @app.errorhandler(404)1175 def page_not_found(error):
4 unmodified lines
1180 @app.errorhandler(DatabaseError)1181 def special_exception_handler(error):1182 return 'Database connection failed', 50011831153 You can also register a function as error handler without using1154 the :meth:`errorhandler` decorator. The following example is1155 equivalent to the one above::11561157 def page_not_found(error):1158 return 'This page does not exist', 4041159 app.error_handler_spec[None][404] = page_not_found11601161 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.11641165 The first ``None`` refers to the active blueprint. If the error1166 handler should be application wide ``None`` shall be used.11671184 .. versionadded:: 0.71185 Use :meth:`register_error_handler` instead of modifying1186 :attr:`error_handler_spec` directly, for application wide error1187 handlers.
10 unmodified lines
1198 self._register_error_handler(None, code_or_exception, f)1199 return f1200 return decorator12011202 @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 lines
1217 :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 )12251226 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 )12331234 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1235 handlers[exc_class] = f1236
96 unmodified lines
13331334 @setupmethod1335 def before_request(self, f):1336 """Registers a function to run before each request.1313 13371338 For example, this can be used to open a database connection, or to load1339 the logged in user from the session.13401341 The function will be called without any arguments. If it returns a
119 unmodified lines
1461 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 14651466 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 14701471 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 lines
1538 exception is not called and it shows up as regular exception in the1539 traceback. This is helpful for debugging implicitly raised HTTP1540 exceptions.15411542 .. versionchanged:: 1.01543 Bad request errors are not trapped by default in debug mode.15441545 .. versionadded:: 0.81546 """1547 if self.config['TRAP_HTTP_EXCEPTIONS']:1548 return True1522 if self.config['TRAP_BAD_REQUEST_ERRORS']:15491550 trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']15511552 # 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)15551556 return False15571558 def handle_user_exception(self, e):1559 """This method is called whenever an exception occurs that should be
2 unmodified lines
1562 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.15651566 .. 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.15691570 .. versionadded:: 0.71571 """1572 exc_type, exc_value, tb = sys.exc_info()1573 assert exc_value is e15381574 # 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.15781579 # 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)15891590 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1591 return self.handle_http_exception(e)15921593 handler = self._find_error_handler(e)
183 unmodified lines
17771778 ``str`` (``unicode`` in Python 2)1779 A response object is created with the string encoded to UTF-81780 as the body.1735 17811782 ``bytes`` (``str`` in Python 2)1783 A response object is created with the bytes as the body.1738 17841785 ``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 17931794 :attr:`response_class`1795 The object is returned unchanged.1750 17961797 other :class:`~werkzeug.wrappers.Response` class1798 The object is coerced to :attr:`response_class`.1753 17991800 :func:`callable`1801 The function is called as a WSGI application. The result is1802 used to create a response object.1803
86 unmodified lines
1890 # 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'])18961897 def inject_url_defaults(self, endpoint, values):1898 """Injects the URL defaults for the given endpoint directly into
33 unmodified lines
1932 """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 19361937 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 lines
1977 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 response19831984 def do_teardown_request(self, exc=_sentinel):1985 """Called after the actual request dispatching and will
76 unmodified lines
20622063 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).20672068 Additional arguments (only if ``base_url`` is not specified):20692070 :param subdomain: subdomain to use for route matching2071 :param url_scheme: scheme for the request, default2072 ``PREFERRED_URL_SCHEME`` or ``http``.2073 """20742075 from flask.testing import make_test_environ_builder20762077 builder = make_test_environ_builder(self, *args, **kwargs)20782079 try:2080 return self.request_context(builder.get_environ())2081 finally:2082 builder.close()
53 unmodified lines
modified:flask/cli.py+71 added-22 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import ast13import inspect14import os15import re16import sys17import traceback18from functools import update_wrapper19from operator import attrgetter
37 unmodified lines
57 ' Use "FLASK_APP={module}:name" to specify the correct'58 ' one.'.format(module=module.__name__)59 )6058 # 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)6462 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 )7778 raise NoAppException(
2 unmodified lines
81 'middleware.'.format(module=module.__name__)82 )838482def 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.85def 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.defaults9394 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()101102103def 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 = attr129130 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))148149150def 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 lines
201 'ensure the extension is .py' % module)202203 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)208158 return app209160210def find_default_import_path():211 app = os.environ.get('FLASK_APP')212 if app is None:213 return
457 unmodified lines
modified:flask/ctx.py+4 added-2 removed
327 unmodified lines
328 # 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)334335 if self.session is None:334 self.session = self.app.make_null_session()336 self.session = session_interface.make_null_session(self.app)337338 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 the
72 unmodified lines
modified:flask/helpers.py-14 removed
1002 unmodified lines
1003 else:1004 return True10051006 return False100710081009def patch_vary_header(response, value):1010 """Add a value to the ``Vary`` header if it is not already present."""10111012 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()10151016 if not any(h.lower() == lower_value for h in headers):1017 headers.append(value)10181019 updated_header = ', '.join(headers)1020 response.headers['Vary'] = updated_header
modified:flask/sessions.py+3 added-4 removed
16 unmodified lines
17from itsdangerous import BadSignature, URLSafeTimedSerializer18from werkzeug.datastructures import CallbackDict19from werkzeug.http import http_date, parse_date2021from flask.helpers import patch_vary_header21from . import Markup, json22from ._compat import iteritems, text_type23from .helpers import is_ip, total_seconds24
320 unmodified lines
345 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']351352 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 lines
464 return465466 # 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')469470 if not self.should_set_cookie(app, session):471 return472
13 unmodified lines
modified:flask/testing.py+32 added-13 removed
19 unmodified lines
20except ImportError:21 from urlparse import urlsplit as url_parse222324def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):24def 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')2930 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".'3435 if base_url is None:36 http_host = app.config.get('SERVER_NAME') or 'localhost'37 app_root = app.config['APPLICATION_ROOT']3839 if subdomain:40 http_host = '{0}.{1}'.format(subdomain, http_host)4142 if url_scheme is None:43 url_scheme = app.config['PREFERRED_URL_SCHEME']4445 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.path5051 if url.query:52 sep = b'?' if isinstance(url.query, bytes) else '?'53 path += sep + url.query5455 return EnvironBuilder(path, base_url, *args, **kwargs)565758class FlaskClient(Client):
45 unmodified lines
104 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 lines
124 finally:125 _request_ctx_stack.pop()126127 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)132133 def open(self, *args, **kwargs):
29 unmodified lines
added:tests/test_apps/cliapp/factory.py+15 added
1from __future__ import absolute_import, print_function23from flask import Flask456def create_app():7 return Flask('create_app')8910def create_app2(foo, bar):11 return Flask("_".join(['create_app2', foo, bar]))121314def 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 lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1312import pickle13import re15import uuid14import time17import flask18import pickle15import uuid16from datetime import datetime17from threading import Thread21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound, Forbidden1819import pytest20import werkzeug.serving21from werkzeug.exceptions import BadRequest, Forbidden, NotFound22from werkzeug.http import parse_date23from werkzeug.routing import BuildError25import werkzeug.serving2425import flask26from flask._compat import text_type272829def test_options_work(app, client):30 @app.route('/', methods=['GET', 'POST'])31 def index():32 return 'Hello World'
496 unmodified lines
529530 @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 response536537 @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 response543544 @app.route('/no-vary-header')
330 unmodified lines
875 assert rv.status_code == 403876 assert b'forbidden' == rv.data877878879def test_error_handler_unknown_code(app):880 with pytest.raises(KeyError) as exc_info:881 app.register_error_handler(999, lambda e: ('999', 999))882883 assert 'Use a subclass' in exc_info.value.args[0]884885886def test_error_handling_processing(app, client):887 app.config['LOGGER_HANDLER_POLICY'] = 'never'888 app.testing = False889
97 unmodified lines
987 @app.route('/fail')988 def fail():989 flask.request.form['missing_key']990991 rv = client.get('/fail')983 assert client.get('/fail').status_code == 400992 assert rv.status_code == 400993 assert b'missing_key' not in rv.data994995 app.config['TRAP_BAD_REQUEST_ERRORS'] = True996997 with pytest.raises(KeyError) as e:998 client.get("/fail")9991000 assert e.errisinstance(BadRequest)1001 assert 'missing_key' in e.value.description100210031004def test_trapping_of_all_http_exceptions(app, client):1005 app.config['TRAP_HTTP_EXCEPTIONS'] = True
830 unmodified lines
modified:tests/test_cli.py+30 added-8 removed
148 unmodified lines
149 """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")184185186def test_find_default_import_path(test_apps, monkeypatch, tmpdir):187 """Test of find_default_import_path."""
181 unmodified lines
modified:tests/test_helpers.py+2 added
42 unmodified lines
43 flask.request.get_json(silent=False, cache=False)4445 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'] = False4849 @app.route('/json', methods=['POST'])50 def post_json():51 flask.request.get_json()
4 unmodified lines
56 assert b'Failed to decode JSON object' in rv.data5758 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'] = False6162 @app.route('/json', methods=['POST'])63 def post_json():64 flask.request.get_json()
868 unmodified lines
modified:tests/test_testing.py+32 added
71 unmodified lines
72 assert rv.data == b'0.0.0.1'73 assert flask.g.user_agent == 'Bar'747576def test_specify_url_scheme(app, client):77 @app.route('/')78 def index():79 return flask.request.url8081 ctx = app.test_request_context(url_scheme='https')82 assert ctx.request.url == 'https://localhost/'8384 rv = client.get('/', url_scheme='https')85 assert rv.data == b'https://localhost/'868788def test_blueprint_with_subdomain(app, client):89 app.config['SERVER_NAME'] = 'example.com:1234'90 app.config['APPLICATION_ROOT'] = '/foo'9192 bp = flask.Blueprint('company', __name__, subdomain='xxx')9394 @bp.route('/')95 def index():96 return flask.request.url9798 app.register_blueprint(bp)99100 ctx = app.test_request_context('/', subdomain='xxx')101 assert ctx.request.url == 'http://xxx.example.com:1234/foo/'102 assert ctx.request.blueprint == bp.name103104 rv = client.get('/', subdomain='xxx')105 assert rv.data == b'http://xxx.example.com:1234/foo/'106107108def test_redirect_keep_session(app, client, app_ctx):109 app.secret_key = 'testing'110111 @app.route('/', methods=['GET', 'POST'])
186 unmodified lines
deleted:.gitmodules-3 removed
1[submodule "docs/_themes"]2 path = docs/_themes3 url = https://github.com/mitsuhiko/flask-sphinx-themes.git
modified:.travis.yml+9 added-33 removed
2 unmodified lines
34matrix: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,codecov2627install:28 - pip install tox29
15 unmodified lines
modified:CHANGES+35 added-9 removed
6 unmodified lines
7------------89Major release, unreleased1011- 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 disable
20 unmodified lines
48- 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`_)6869.. _#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/23488788Version 0.12.289--------------90
617 unmodified lines
modified:CONTRIBUTING.rst+93 added-92 removed
1==========================1How to contribute to Flask2==========================35Thanks for considering contributing to Flask.4Thank you for considering contributing to Flask!56Support questions8=================7-----------------810Please, don't use the issue tracker for this. Check whether the ``#pocoo`` IRC11channel on Freenode can help with your issue. If your problem is not strictly12Werkzeug or Flask specific, ``#python`` is generally more active.13`Stack Overflow <https://stackoverflow.com/>`_ is also worth considering.9Please, don't use the issue tracker for this. Use one of the following10resources for questions about your own code:1112* The IRC channel ``#pocoo`` on FreeNode.13* The IRC channel ``#python`` on FreeNode for more general questions.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.}``1718.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked1920Reporting issues16================21----------------2218- 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.3121- 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/mcve3334Submitting patches25==================35------------------3637- 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.4231- 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.3343First time setup35----------------44~~~~~~~~~~~~~~~~4546- Download and install the `latest version of git`_.38- Configure git with your `username`_ and `email`_.47- Configure git with your `username`_ and `email`_::4849 git config --global user.name 'your name'50 git config --global user.email 'your email'5152- 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::5556 git clone https://github.com/{username}/flask57 cd flask5859- Add the main repository as a remote to update later::6061 git remote add pallets https://github.com/pallets/flask62 git fetch pallets6364- Create a virtualenv::6566 python3 -m venv env67 . env/bin/activate68 # or "env\Scripts\activate" on Windows6970- Install Flask in editable mode with development dependencies::7172 pip install -e ".[dev]"7374.. _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-fork8081Start coding53------------82~~~~~~~~~~~~8384- 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 lines
96.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/9798.. _contributing-testsuite:9971Running the testsuite72---------------------100Running the tests101~~~~~~~~~~~~~~~~~10274You probably want to set up a `virtualenv75<https://virtualenv.readthedocs.io/en/latest/index.html>`_.103Run the basic test suite with::10477The minimal requirement for running the testsuite is ``pytest``. You can78install it with::105 pytest10680 pip install pytest107This only runs the tests for the current environment. Whether this is relevant108depends on which part of Flask you're working on. Travis-CI will run the full109suite when you submit your pull request.11082Clone this repository::111The full test suite takes a long time to run because it tests multiple112combinations of Python and dependencies. You need to have Python 2.6, 2.7, 3.3,1133.4, 3.5 3.6, and PyPy 2.7 installed to run all of the environments. Then run::11484 git clone https://github.com/pallets/flask.git115 tox11686Install Flask as an editable package using the current source::8788 cd flask89 pip install --editable .9091Running the testsuite92---------------------9394The minimal requirement for running the testsuite is ``pytest``. You can95install it with::9697 pip install pytest9899Then you can run the testsuite with::100101 pytest tests/102103**Shortcut**: ``make test`` will ensure ``pytest`` is installed, and run it.104105With only pytest installed, a large part of the testsuite will get skipped106though. Whether this is relevant depends on which part of Flask you're working107on. Travis is set up to run the full testsuite when you submit your pull108request anyways.109110If you really want to test everything, you will have to install ``tox`` instead111of ``pytest``. You can install it with::112113 pip install tox114115The ``tox`` command will then run all tests against multiple combinations116Python versions and dependency versions.117118**Shortcut**: ``make tox-test`` will ensure ``tox`` is installed, and run it.119117Running test coverage121---------------------122Generating a report of lines that do not have unit test coverage can indicate where123to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``124plugin. This assumes you have already run the testsuite (see previous section)::118~~~~~~~~~~~~~~~~~~~~~119126 pip install pytest-cov120Generating a report of lines that do not have test coverage can indicate121where to start contributing. Run ``pytest`` using ``coverage`` and generate a122report on the terminal and as an interactive HTML document::123128After 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.html128130 pytest --cov=flask tests/129Read more about `coverage <https://coverage.readthedocs.io>`_.130132Generate a HTML report can be done using this command::131Running the full test suite with ``tox`` will combine the coverage reports132from all runs.133134 pytest --cov-report html --cov=flask tests/134``make`` targets135~~~~~~~~~~~~~~~~136136Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io137Flask provides a ``Makefile`` with various shortcuts. They will ensure that138all dependencies are installed.139138**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 documentation144145Caution: zero-padded file modes146-------------------------------147141Caution142=======143pushing144-------145This 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.148This repository contains several zero-padded file modes that may cause issues149when pushing this repository to git hosts other than GitHub. Fixing this is150destructive to the commit history, so we suggest ignoring these warnings. If it151fails to push and you're using a self-hosted git service like GitLab, you can152turn off repository checks in the admin panel.153154These files can also cause issues while cloning. If you have ::155148cloning149-------150The zero-padded file modes files above can cause issues while cloning, too. If you have151152::153156 [fetch]157 fsckobjects = true158157or159or ::160159::160161 [receive]162 fsckObjects = true163164165set 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.164set in your git configuration file, cloning this repository will fail. The only165solution is to set both of the above settings to false while cloning, and then166setting 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 ebook23all: clean-pyc test3all: test45test:6 pip install -r test-requirements.txt7 tox -e py-release5install-dev:6 pip install -q -e .[dev]79cov:10 pip install -r test-requirements.txt -q11 FLASK_DEBUG= py.test --cov-report term --cov-report html --cov=flask --cov=examples tests examples8test: clean-pyc install-dev9 pytest1011coverage: clean-pyc install-dev12 pip install -q -e .[test]13 coverage run -m pytest14 coverage report15 coverage html1617cov: coverage1819test-all: install-dev20 tox2122tox: test-all2324docs: clean-pyc install-dev25 $(MAKE) -C docs html2627audit:28 python setup.py audit2930release:31 python scripts/make-release.py3219ext-test:20 python tests/flaskext_test.py --browse2133clean-pyc:34 find . -name '*.pyc' -exec rm -f {} +35 find . -name '*.pyo' -exec rm -f {} +36 find . -name '*~' -exec rm -f {} +
13 unmodified lines
50 @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'4344docs:45 $(MAKE) -C docs html
modified:setup.py+12 added-2 removed
46 unmodified lines
47import re48import ast49from setuptools import setup505151_version_re = re.compile(r'__version__\s+=\s+(.*)')5253with open('flask/__init__.py', 'rb') as f:54 version = str(ast.literal_eval(_version_re.search(55 f.read().decode('utf-8')).group(1)))565857setup(58 name='Flask',59 version=version,60 url='https://github.com/pallets/flask/',
12 unmodified lines
73 '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 lines
98 '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 lines
modified:tox.ini+11 added-6 removed
1[tox]2envlist =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-report
25 unmodified lines
34 pip install -e examples/minitwit -q35 pip install -e examples/patterns/largerapp -q3637 # pytest-cov doesn't seem to play nice with -p38 coverage run -p -m pytest38 coverage run -p -m pytest tests examples3940[testenv:docs-html]41deps =42 sphinx43 flask-sphinx-themes41deps = sphinx42commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html4344[testenv:docs-linkcheck]45deps = sphinx
14 unmodified lines
60commands =61 coverage combine62 coverage report63 codecov6465[testenv:detox]66skip_install = true67deps = detox68commands =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