Skip to content
Myr

upgrading.rst

This file

Path

docs/upgrading.rst

472 lines · 19.1 KiB

Last changed by

Merge pull request #2019 from pallets/bugfix/sendfile-errorArmin Ronacherbefore adoptiona40489e

History of this file

Take it

The walk stopped after 200 commits: lines older than f63cd72 point at it.

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 1–16why, one step back
1Upgrading to Newer Releases
2===========================34Flask itself is changing like any software is changing over time. Most of5the changes are the nice kind, the kind where you don't have to change6anything in your code to profit from a new release.78However every once in a while there are changes that do require some9changes in your code or there are changes that make it possible for you to10improve your own code quality by taking advantage of new features in11Flask.1213This section of the documentation enumerates all the changes in Flask from14release to release and how you can change your code to have a painless15updating experience.16

Update documentation for upgrading Flask using 'pip' command (#1918)Ameya Pandilwarbefore adoption663d786

line 17why, one step back
17Use the :command:`pip` command to upgrade your existing Flask installation by

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 18why, one step back
18providing the ``--upgrade`` parameter::

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

line 19why, one step back
19

Update documentation for upgrading Flask using 'pip' command (#1918)Ameya Pandilwarbefore adoption663d786

line 20why, one step back
20 $ pip install --upgrade Flask

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

line 21why, one step back
21

Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be

lines 22–56why, one step back
22.. _upgrading-to-012:
2324Version 0.1225------------2627Changes to send_file28````````````````````2930The ``filename`` is no longer automatically inferred from file-like objects.31This means that the following code will no longer automatically have32``X-Sendfile`` support, etag generation or MIME-type guessing::3334 response = send_file(open('/path/to/file.txt'))3536Any of the following is functionally equivalent::3738 fname = '/path/to/file.txt'3940 # Just pass the filepath directly41 response = send_file(fname)4243 # Set the MIME-type and ETag explicitly44 response = send_file(open(fname), mimetype='text/plain')45 response.set_etag(...)4647 # Set `attachment_filename` for MIME-type guessing48 # ETag still needs to be manually set49 response = send_file(open(fname), attachment_filename=fname)50 response.set_etag(...)5152The reason for this is that some file-like objects have a invalid or even53misleading ``name`` attribute. Silently swallowing errors in such cases was not54a satisfying solution.5556Additionally the default of falling back to ``application/octet-stream`` has

Merge pull request #2019 from pallets/bugfix/sendfile-errorArmin Ronacherbefore adoptiona40489e

lines 57–58why, one step back
57been restricted. If Flask can't guess one or the user didn't provide one, the
58function fails if no filename information was provided.

Properly remove f.name usage in send_file (#1988)Markus Unterwaditzerbefore adoption71e10be

lines 59–60why, one step back
59
60.. _upgrading-to-011:

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

line 61why, one step back
61

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

lines 62–63why, one step back
62Version 0.11
63------------

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

line 64why, one step back
64

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

lines 65–70why, one step back
650.11 is an odd release in the Flask release cycle because it was supposed
66to be the 1.0 release. However because there was such a long lead time up67to the release we decided to push out a 0.11 release first with some68changes removed to make the transition easier. If you have been tracking69the master branch which was 1.0 you might see some unexpected changes.70

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 71why, one step back
71In case you did track the master branch you will notice that :command:`flask --app`

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

lines 72–74why, one step back
72is removed now. You need to use the environment variable to specify an
73application.74

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 75why, one step back
75Debugging

fix some warnings while building docsDavid Lordbefore adoption317d603

line 76why, one step back
76`````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 77why, one step back
77

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

line 78why, one step back
78Flask 0.11 removed the ``debug_log_format`` attribute from Flask

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 79–82why, one step back
79applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can
80be used to disable the default log handlers and custom log handlers can be81set up.82

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 83why, one step back
83Error handling

fix some warnings while building docsDavid Lordbefore adoption317d603

line 84why, one step back
84``````````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 85why, one step back
85

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 86–93why, one step back
86The behavior of error handlers was changed.
87The precedence of handlers used to be based on the decoration/call order of88:meth:`~flask.Flask.errorhandler` and89:meth:`~flask.Flask.register_error_handler`, respectively.90Now the inheritance hierarchy takes precedence and handlers for more91specific exception classes are executed instead of more general ones.92See :ref:`error-handlers` for specifics.93

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 94why, one step back
94Trying to register a handler on an instance now raises :exc:`ValueError`.

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 95–101why, one step back
95
96.. note::9798 There used to be a logic error allowing you to register handlers99 only for exception *instances*. This was unintended and plain wrong,100 and therefore was replaced with the intended behavior of registering101 handlers only using exception classes and HTTP error codes.

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

lines 102–103why, one step back
102
103Templating

fix some warnings while building docsDavid Lordbefore adoption317d603

line 104why, one step back
104``````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

lines 105–108why, one step back
105
106The :func:`~flask.templating.render_template_string` function has changed to107autoescape template variables by default. This better matches the behavior108of :func:`~flask.templating.render_template`.

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 109why, one step back
109

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 110why, one step back
110Extension imports

fix some warnings while building docsDavid Lordbefore adoption317d603

line 111why, one step back
111`````````````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

lines 112–118why, one step back
112
113Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114``flask_foo``.115116The old form still works, but Flask will issue a117``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118way. We also provide a migration utility called `flask-ext-migrate

Remove extmigrate from Flask repoKeyan Pishdadianbefore adoption1a877fb

line 119why, one step back
119<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 120why, one step back
120automatically rewrite your imports for this.

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 121–173why, one step back
121
122.. _upgrading-to-010:123124Version 0.10125------------126127The biggest change going from 0.9 to 0.10 is that the cookie serialization128format changed from pickle to a specialized JSON format. This change has129been done in order to avoid the damage an attacker can do if the secret130key is leaked. When you upgrade you will notice two major changes: all131sessions that were issued before the upgrade are invalidated and you can132only store a limited amount of types in the session. The new sessions are133by design much more restricted to only allow JSON with a few small134extensions for tuples and strings with HTML markup.135136In order to not break people's sessions it is possible to continue using137the old session system by using the `Flask-OldSessions`_ extension.138139Flask also started storing the :data:`flask.g` object on the application140context instead of the request context. This change should be transparent141for you but it means that you now can store things on the ``g`` object142when there is no request context yet but an application context. The old143``flask.Flask.request_globals_class`` attribute was renamed to144:attr:`flask.Flask.app_ctx_globals_class`.145146.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/147148Version 0.9149-----------150151The behavior of returning tuples from a function was simplified. If you152return a tuple it no longer defines the arguments for the response object153you're creating, it's now always a tuple in the form ``(response, status,154headers)`` where at least one item has to be provided. If you depend on155the old behavior, you can add it easily by subclassing Flask::156157 class TraditionalFlask(Flask):158 def make_response(self, rv):159 if isinstance(rv, tuple):160 return self.response_class(*rv)161 return Flask.make_response(self, rv)162163If you maintain an extension that was using :data:`~flask._request_ctx_stack`164before, please consider changing to :data:`~flask._app_ctx_stack` if it makes165sense for your extension. For instance, the app context stack makes sense for166extensions which connect to databases. Using the app context stack instead of167the request context stack will make extensions more readily handle use cases168outside of requests.169170Version 0.8171-----------172173Flask introduced a new session interface system. We also noticed that

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 174why, one step back
174there was a naming collision between ``flask.session`` the module that

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 175–217why, one step back
175implements sessions and :data:`flask.session` which is the global session
176object. With that introduction we moved the implementation details for177the session system into a new module called :mod:`flask.sessions`. If you178used the previously undocumented session support we urge you to upgrade.179180If invalid JSON data was submitted Flask will now raise a181:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the182default :exc:`ValueError` bubble up. This has the advantage that you no183longer have to handle that error to avoid an internal server error showing184up for the user. If you were catching this down explicitly in the past185as :exc:`ValueError` you will need to change this.186187Due to a bug in the test client Flask 0.7 did not trigger teardown188handlers when the test client was used in a with statement. This was189since fixed but might require some changes in your test suites if you190relied on this behavior.191192Version 0.7193-----------194195In Flask 0.7 we cleaned up the code base internally a lot and did some196backwards incompatible changes that make it easier to implement larger197applications with Flask. Because we want to make upgrading as easy as198possible we tried to counter the problems arising from these changes by199providing a script that can ease the transition.200201The script scans your whole application and generates an unified diff with202changes it assumes are safe to apply. However as this is an automated203tool it won't be able to find all use cases and it might miss some. We204internally spread a lot of deprecation warnings all over the place to make205it easy to find pieces of code that it was unable to upgrade.206207We strongly recommend that you hand review the generated patchfile and208only apply the chunks that look good.209210If you are using git as version control system for your project we211recommend applying the patch with ``path -p1 < patchfile.diff`` and then212using the interactive commit feature to only apply the chunks that look213good.214215To apply the upgrade script do the following:2162171. Download the script: `flask-07-upgrade.py

Change to Pallets projectJosé Carlos Garcíabefore adoption567fff9

line 218why, one step back
218 <https://raw.githubusercontent.com/pallets/flask/master/scripts/flask-07-upgrade.py>`_

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 219–239why, one step back
2192. Run it in the directory of your application::
220221 python flask-07-upgrade.py > patchfile.diff2222233. Review the generated patchfile.2244. Apply the patch::225226 patch -p1 < patchfile.diff2272285. If you were using per-module template folders you need to move some229 templates around. Previously if you had a folder named :file:`templates`230 next to a blueprint named ``admin`` the implicit template path231 automatically was :file:`admin/index.html` for a template file called232 :file:`templates/index.html`. This no longer is the case. Now you need233 to name the template :file:`templates/admin/index.html`. The tool will234 not detect this so you will have to do that on your own.235236Please note that deprecation warnings are disabled by default starting237with Python 2.7. In order to see the deprecation warnings that might be238emitted you have to enabled them with the :mod:`warnings` module.239

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 240why, one step back
240If you are working with windows and you lack the ``patch`` command line

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 241–256why, one step back
241utility you can get it as part of various Unix runtime environments for
242windows including cygwin, msysgit or ming32. Also source control systems243like svn, hg or git have builtin support for applying unified diffs as244generated by the tool. Check the manual of your version control system245for more information.246247Bug in Request Locals248`````````````````````249250Due to a bug in earlier implementations the request local proxies now251raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they252are unbound. If you caught these exceptions with :exc:`AttributeError`253before, you should catch them with :exc:`RuntimeError` now.254255Additionally the :func:`~flask.send_file` function is now issuing256deprecation warnings if you depend on functionality that will be removed

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

line 257why, one step back
257in Flask 0.11. Previously it was possible to use etags and mimetypes

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 258–356why, one step back
258when file objects were passed. This was unreliable and caused issues
259for a few setups. If you get a deprecation warning, make sure to260update your application to work with either filenames there or disable261etag attaching and attach them yourself.262263Old code::264265 return send_file(my_file_object)266 return send_file(my_file_object)267268New code::269270 return send_file(my_file_object, add_etags=False)271272.. _upgrading-to-new-teardown-handling:273274Upgrading to new Teardown Handling275``````````````````````````````````276277We streamlined the behavior of the callbacks for request handling. For278things that modify the response the :meth:`~flask.Flask.after_request`279decorators continue to work as expected, but for things that absolutely280must happen at the end of request we introduced the new281:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that282change also made after-request work differently under error conditions.283It's not consistently skipped if exceptions happen whereas previously it284might have been called twice to ensure it is executed at the end of the285request.286287If you have database connection code that looks like this::288289 @app.after_request290 def after_request(response):291 g.db.close()292 return response293294You are now encouraged to use this instead::295296 @app.teardown_request297 def after_request(exception):298 if hasattr(g, 'db'):299 g.db.close()300301On the upside this change greatly improves the internal code flow and302makes it easier to customize the dispatching and error handling. This303makes it now a lot easier to write unit tests as you can prevent closing304down of database connections for a while. You can take advantage of the305fact that the teardown callbacks are called when the response context is306removed from the stack so a test can query the database after request307handling::308309 with app.test_client() as client:310 resp = client.get('/')311 # g.db is still bound if there is such a thing312313 # and here it's gone314315Manual Error Handler Attaching316``````````````````````````````317318While it is still possible to attach error handlers to319:attr:`Flask.error_handlers` it's discouraged to do so and in fact320deprecated. In general we no longer recommend custom error handler321attaching via assignments to the underlying dictionary due to the more322complex internal handling to support arbitrary exception classes and323blueprints. See :meth:`Flask.errorhandler` for more information.324325The proper upgrade is to change this::326327 app.error_handlers[403] = handle_error328329Into this::330331 app.register_error_handler(403, handle_error)332333Alternatively you should just attach the function with a decorator::334335 @app.errorhandler(403)336 def handle_error(e):337 ...338339(Note that :meth:`register_error_handler` is new in Flask 0.7)340341Blueprint Support342`````````````````343344Blueprints replace the previous concept of “Modules” in Flask. They345provide better semantics for various features and work better with large346applications. The update script provided should be able to upgrade your347applications automatically, but there might be some cases where it fails348to upgrade. What changed?349350- Blueprints need explicit names. Modules had an automatic name351 guessing scheme where the shortname for the module was taken from the352 last part of the import module. The upgrade script tries to guess353 that name but it might fail as this information could change at354 runtime.355- Blueprints have an inverse behavior for :meth:`url_for`. Previously356 ``.foo`` told :meth:`url_for` that it should look for the endpoint

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 357why, one step back
357 ``foo`` on the application. Now it means “relative to current module”.

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 358–374why, one step back
358 The script will inverse all calls to :meth:`url_for` automatically for
359 you. It will do this in a very eager way so you might end up with360 some unnecessary leading dots in your code if you're not using361 modules.362- Blueprints do not automatically provide static folders. They will363 also no longer automatically export templates from a folder called364 :file:`templates` next to their location however but it can be enabled from365 the constructor. Same with static files: if you want to continue366 serving static files you need to tell the constructor explicitly the367 path to the static folder (which can be relative to the blueprint's368 module path).369- Rendering templates was simplified. Now the blueprints can provide370 template folders which are added to a general template searchpath.371 This means that you need to add another subfolder with the blueprint's372 name into that folder if you want :file:`blueprintname/template.html` as373 the template name.374

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 375why, one step back
375If you continue to use the ``Module`` object which is deprecated, Flask will

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 376–394why, one step back
376restore the previous behavior as good as possible. However we strongly
377recommend upgrading to the new blueprints as they provide a lot of useful378improvement such as the ability to attach a blueprint multiple times,379blueprint specific error handlers and a lot more.380381382Version 0.6383-----------384385Flask 0.6 comes with a backwards incompatible change which affects the386order of after-request handlers. Previously they were called in the order387of the registration, now they are called in reverse order. This change388was made so that Flask behaves more like people expected it to work and389how other systems handle request pre- and post-processing. If you390depend on the order of execution of post-request functions, be sure to391change the order.392393Another change that breaks backwards compatibility is that context394processors will no longer override values passed directly to the template

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 395why, one step back
395rendering function. If for example ``request`` is as variable passed

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 396–420why, one step back
396directly to the template, the default context processor will not override
397it with the current request object. This makes it easier to extend398context processors later to inject additional variables without breaking399existing template not expecting them.400401Version 0.5402-----------403404Flask 0.5 is the first release that comes as a Python package instead of a405single module. There were a couple of internal refactoring so if you406depend on undocumented internal details you probably have to adapt the407imports.408409The following changes may be relevant to your application:410411- autoescaping no longer happens for all templates. Instead it is412 configured to only happen on files ending with ``.html``, ``.htm``,413 ``.xml`` and ``.xhtml``. If you have templates with different414 extensions you should override the415 :meth:`~flask.Flask.select_jinja_autoescape` method.416- Flask no longer supports zipped applications in this release. This417 functionality might come back in future releases if there is demand418 for this feature. Removing support for this makes the Flask internal419 code easier to understand and fixes a couple of small issues that make420 debugging harder than necessary.

clean up code formatting in some docsDavid Lordbefore adoption1928f28

line 421why, one step back
421- The ``create_jinja_loader`` function is gone. If you want to customize

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

lines 422–472why, one step back
422 the Jinja loader now, use the
423 :meth:`~flask.Flask.create_jinja_environment` method instead.424425Version 0.4426-----------427428For application developers there are no changes that require changes in429your code. In case you are developing on a Flask extension however, and430that extension has a unittest-mode you might want to link the activation431of that mode to the new ``TESTING`` flag.432433Version 0.3434-----------435436Flask 0.3 introduces configuration support and logging as well as437categories for flashing messages. All these are features that are 100%438backwards compatible but you might want to take advantage of them.439440Configuration Support441`````````````````````442443The configuration support makes it easier to write any kind of application444that requires some sort of configuration. (Which most likely is the case445for any application out there).446447If you previously had code like this::448449 app.debug = DEBUG450 app.secret_key = SECRET_KEY451452You no longer have to do that, instead you can just load a configuration453into the config object. How this works is outlined in :ref:`config`.454455Logging Integration456```````````````````457458Flask now configures a logger for you with some basic and useful defaults.459If you run your application in production and want to profit from460automatic error logging, you might be interested in attaching a proper log461handler. Also you can start logging warnings and errors into the logger462when appropriately. For more information on that, read463:ref:`application-errors`.464465Categories for Flash Messages466`````````````````````````````467468Flash messages can now have categories attached. This makes it possible469to render errors, warnings or regular messages differently for example.470This is an opt-in feature because it requires some rethinking in the code.471472Read all about that in the :ref:`message-flashing-pattern` pattern.