Skip to content
Myr

upgrading.rst

This file

Path

docs/upgrading.rst

434 lines · 17.9 KiB

Last changed by

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

History of this file

Take it

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

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 1–23why, 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.1617If you want to use the :command:`easy_install` command to upgrade your Flask18installation, make sure to pass it the :option:`-U` parameter::1920 $ easy_install -U Flask2122.. _upgrading-to-10:23

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

lines 24–25why, one step back
24Version 0.11
25------------

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 26why, one step back
26

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

lines 27–36why, one step back
270.11 is an odd release in the Flask release cycle because it was supposed
28to be the 1.0 release. However because there was such a long lead time up29to the release we decided to push out a 0.11 release first with some30changes removed to make the transition easier. If you have been tracking31the master branch which was 1.0 you might see some unexpected changes.3233In case you did track the master branch you will notice that `flask --app`34is removed now. You need to use the environment variable to specify an35application.36

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 37why, one step back
37Debugging

fix some warnings while building docsDavid Lordbefore adoption317d603

line 38why, one step back
38`````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 39why, one step back
39

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

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

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 41–44why, one step back
41applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can
42be used to disable the default log handlers and custom log handlers can be43set up.44

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 45why, one step back
45Error handling

fix some warnings while building docsDavid Lordbefore adoption317d603

line 46why, one step back
46``````````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 47why, one step back
47

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

lines 48–55why, one step back
48The behavior of error handlers was changed.
49The precedence of handlers used to be based on the decoration/call order of50:meth:`~flask.Flask.errorhandler` and51:meth:`~flask.Flask.register_error_handler`, respectively.52Now the inheritance hierarchy takes precedence and handlers for more53specific exception classes are executed instead of more general ones.54See :ref:`error-handlers` for specifics.55

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

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

Merge branch 'alanhamlett-master'Markus Unterwaditzerbefore adoptiondb09c67

line 57why, one step back
57

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

lines 58–63why, one step back
58.. note::
5960 There used to be a logic error allowing you to register handlers61 only for exception *instances*. This was unintended and plain wrong,62 and therefore was replaced with the intended behavior of registering63 handlers only using exception classes and HTTP error codes.

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

lines 64–65why, one step back
64
65Templating

fix some warnings while building docsDavid Lordbefore adoption317d603

line 66why, one step back
66``````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

lines 67–70why, one step back
67
68The :func:`~flask.templating.render_template_string` function has changed to69autoescape template variables by default. This better matches the behavior70of :func:`~flask.templating.render_template`.

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

line 71why, one step back
71

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

line 72why, one step back
72Extension imports

fix some warnings while building docsDavid Lordbefore adoption317d603

line 73why, one step back
73`````````````````

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

lines 74–80why, one step back
74
75Extension imports of the form ``flask.ext.foo`` are deprecated, you should use76``flask_foo``.7778The old form still works, but Flask will issue a79``flask.exthook.ExtDeprecationWarning`` for each extension you import the old80way. We also provide a migration utility called `flask-ext-migrate

Remove extmigrate from Flask repoKeyan Pishdadianbefore adoption1a877fb

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

Deprecate flask.extMarkus Unterwaditzerbefore adoptiond3d8a46

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

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

line 83why, one step back
83

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 84–179why, one step back
84.. _upgrading-to-010:
8586Version 0.1087------------8889The biggest change going from 0.9 to 0.10 is that the cookie serialization90format changed from pickle to a specialized JSON format. This change has91been done in order to avoid the damage an attacker can do if the secret92key is leaked. When you upgrade you will notice two major changes: all93sessions that were issued before the upgrade are invalidated and you can94only store a limited amount of types in the session. The new sessions are95by design much more restricted to only allow JSON with a few small96extensions for tuples and strings with HTML markup.9798In order to not break people's sessions it is possible to continue using99the old session system by using the `Flask-OldSessions`_ extension.100101Flask also started storing the :data:`flask.g` object on the application102context instead of the request context. This change should be transparent103for you but it means that you now can store things on the ``g`` object104when there is no request context yet but an application context. The old105``flask.Flask.request_globals_class`` attribute was renamed to106:attr:`flask.Flask.app_ctx_globals_class`.107108.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/109110Version 0.9111-----------112113The behavior of returning tuples from a function was simplified. If you114return a tuple it no longer defines the arguments for the response object115you're creating, it's now always a tuple in the form ``(response, status,116headers)`` where at least one item has to be provided. If you depend on117the old behavior, you can add it easily by subclassing Flask::118119 class TraditionalFlask(Flask):120 def make_response(self, rv):121 if isinstance(rv, tuple):122 return self.response_class(*rv)123 return Flask.make_response(self, rv)124125If you maintain an extension that was using :data:`~flask._request_ctx_stack`126before, please consider changing to :data:`~flask._app_ctx_stack` if it makes127sense for your extension. For instance, the app context stack makes sense for128extensions which connect to databases. Using the app context stack instead of129the request context stack will make extensions more readily handle use cases130outside of requests.131132Version 0.8133-----------134135Flask introduced a new session interface system. We also noticed that136there was a naming collision between `flask.session` the module that137implements sessions and :data:`flask.session` which is the global session138object. With that introduction we moved the implementation details for139the session system into a new module called :mod:`flask.sessions`. If you140used the previously undocumented session support we urge you to upgrade.141142If invalid JSON data was submitted Flask will now raise a143:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the144default :exc:`ValueError` bubble up. This has the advantage that you no145longer have to handle that error to avoid an internal server error showing146up for the user. If you were catching this down explicitly in the past147as :exc:`ValueError` you will need to change this.148149Due to a bug in the test client Flask 0.7 did not trigger teardown150handlers when the test client was used in a with statement. This was151since fixed but might require some changes in your test suites if you152relied on this behavior.153154Version 0.7155-----------156157In Flask 0.7 we cleaned up the code base internally a lot and did some158backwards incompatible changes that make it easier to implement larger159applications with Flask. Because we want to make upgrading as easy as160possible we tried to counter the problems arising from these changes by161providing a script that can ease the transition.162163The script scans your whole application and generates an unified diff with164changes it assumes are safe to apply. However as this is an automated165tool it won't be able to find all use cases and it might miss some. We166internally spread a lot of deprecation warnings all over the place to make167it easy to find pieces of code that it was unable to upgrade.168169We strongly recommend that you hand review the generated patchfile and170only apply the chunks that look good.171172If you are using git as version control system for your project we173recommend applying the patch with ``path -p1 < patchfile.diff`` and then174using the interactive commit feature to only apply the chunks that look175good.176177To apply the upgrade script do the following:1781791. Download the script: `flask-07-upgrade.py

Change to Pallets projectJosé Carlos Garcíabefore adoption567fff9

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

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 181–218why, one step back
1812. Run it in the directory of your application::
182183 python flask-07-upgrade.py > patchfile.diff1841853. Review the generated patchfile.1864. Apply the patch::187188 patch -p1 < patchfile.diff1891905. If you were using per-module template folders you need to move some191 templates around. Previously if you had a folder named :file:`templates`192 next to a blueprint named ``admin`` the implicit template path193 automatically was :file:`admin/index.html` for a template file called194 :file:`templates/index.html`. This no longer is the case. Now you need195 to name the template :file:`templates/admin/index.html`. The tool will196 not detect this so you will have to do that on your own.197198Please note that deprecation warnings are disabled by default starting199with Python 2.7. In order to see the deprecation warnings that might be200emitted you have to enabled them with the :mod:`warnings` module.201202If you are working with windows and you lack the `patch` command line203utility you can get it as part of various Unix runtime environments for204windows including cygwin, msysgit or ming32. Also source control systems205like svn, hg or git have builtin support for applying unified diffs as206generated by the tool. Check the manual of your version control system207for more information.208209Bug in Request Locals210`````````````````````211212Due to a bug in earlier implementations the request local proxies now213raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they214are unbound. If you caught these exceptions with :exc:`AttributeError`215before, you should catch them with :exc:`RuntimeError` now.216217Additionally the :func:`~flask.send_file` function is now issuing218deprecation warnings if you depend on functionality that will be removed

1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe

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

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 220–312why, one step back
220when file objects were passed. This was unreliable and caused issues
221for a few setups. If you get a deprecation warning, make sure to222update your application to work with either filenames there or disable223etag attaching and attach them yourself.224225Old code::226227 return send_file(my_file_object)228 return send_file(my_file_object)229230New code::231232 return send_file(my_file_object, add_etags=False)233234.. _upgrading-to-new-teardown-handling:235236Upgrading to new Teardown Handling237``````````````````````````````````238239We streamlined the behavior of the callbacks for request handling. For240things that modify the response the :meth:`~flask.Flask.after_request`241decorators continue to work as expected, but for things that absolutely242must happen at the end of request we introduced the new243:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that244change also made after-request work differently under error conditions.245It's not consistently skipped if exceptions happen whereas previously it246might have been called twice to ensure it is executed at the end of the247request.248249If you have database connection code that looks like this::250251 @app.after_request252 def after_request(response):253 g.db.close()254 return response255256You are now encouraged to use this instead::257258 @app.teardown_request259 def after_request(exception):260 if hasattr(g, 'db'):261 g.db.close()262263On the upside this change greatly improves the internal code flow and264makes it easier to customize the dispatching and error handling. This265makes it now a lot easier to write unit tests as you can prevent closing266down of database connections for a while. You can take advantage of the267fact that the teardown callbacks are called when the response context is268removed from the stack so a test can query the database after request269handling::270271 with app.test_client() as client:272 resp = client.get('/')273 # g.db is still bound if there is such a thing274275 # and here it's gone276277Manual Error Handler Attaching278``````````````````````````````279280While it is still possible to attach error handlers to281:attr:`Flask.error_handlers` it's discouraged to do so and in fact282deprecated. In general we no longer recommend custom error handler283attaching via assignments to the underlying dictionary due to the more284complex internal handling to support arbitrary exception classes and285blueprints. See :meth:`Flask.errorhandler` for more information.286287The proper upgrade is to change this::288289 app.error_handlers[403] = handle_error290291Into this::292293 app.register_error_handler(403, handle_error)294295Alternatively you should just attach the function with a decorator::296297 @app.errorhandler(403)298 def handle_error(e):299 ...300301(Note that :meth:`register_error_handler` is new in Flask 0.7)302303Blueprint Support304`````````````````305306Blueprints replace the previous concept of “Modules” in Flask. They307provide better semantics for various features and work better with large308applications. The update script provided should be able to upgrade your309applications automatically, but there might be some cases where it fails310to upgrade. What changed?311312- Blueprints need explicit names. Modules had an automatic name

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

line 313why, one step back
313 guessing scheme where the shortname for the module was taken from the

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 314–350why, one step back
314 last part of the import module. The upgrade script tries to guess
315 that name but it might fail as this information could change at316 runtime.317- Blueprints have an inverse behavior for :meth:`url_for`. Previously318 ``.foo`` told :meth:`url_for` that it should look for the endpoint319 `foo` on the application. Now it means “relative to current module”.320 The script will inverse all calls to :meth:`url_for` automatically for321 you. It will do this in a very eager way so you might end up with322 some unnecessary leading dots in your code if you're not using323 modules.324- Blueprints do not automatically provide static folders. They will325 also no longer automatically export templates from a folder called326 :file:`templates` next to their location however but it can be enabled from327 the constructor. Same with static files: if you want to continue328 serving static files you need to tell the constructor explicitly the329 path to the static folder (which can be relative to the blueprint's330 module path).331- Rendering templates was simplified. Now the blueprints can provide332 template folders which are added to a general template searchpath.333 This means that you need to add another subfolder with the blueprint's334 name into that folder if you want :file:`blueprintname/template.html` as335 the template name.336337If you continue to use the `Module` object which is deprecated, Flask will338restore the previous behavior as good as possible. However we strongly339recommend upgrading to the new blueprints as they provide a lot of useful340improvement such as the ability to attach a blueprint multiple times,341blueprint specific error handlers and a lot more.342343344Version 0.6345-----------346347Flask 0.6 comes with a backwards incompatible change which affects the348order of after-request handlers. Previously they were called in the order349of the registration, now they are called in reverse order. This change350was made so that Flask behaves more like people expected it to work and

Merge pull request #1418 from alexwlchan/masterKeyan Pishdadianbefore adoptiondac45f6

line 351why, one step back
351how other systems handle request pre- and post-processing. If you

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

lines 352–434why, one step back
352depend on the order of execution of post-request functions, be sure to
353change the order.354355Another change that breaks backwards compatibility is that context356processors will no longer override values passed directly to the template357rendering function. If for example `request` is as variable passed358directly to the template, the default context processor will not override359it with the current request object. This makes it easier to extend360context processors later to inject additional variables without breaking361existing template not expecting them.362363Version 0.5364-----------365366Flask 0.5 is the first release that comes as a Python package instead of a367single module. There were a couple of internal refactoring so if you368depend on undocumented internal details you probably have to adapt the369imports.370371The following changes may be relevant to your application:372373- autoescaping no longer happens for all templates. Instead it is374 configured to only happen on files ending with ``.html``, ``.htm``,375 ``.xml`` and ``.xhtml``. If you have templates with different376 extensions you should override the377 :meth:`~flask.Flask.select_jinja_autoescape` method.378- Flask no longer supports zipped applications in this release. This379 functionality might come back in future releases if there is demand380 for this feature. Removing support for this makes the Flask internal381 code easier to understand and fixes a couple of small issues that make382 debugging harder than necessary.383- The `create_jinja_loader` function is gone. If you want to customize384 the Jinja loader now, use the385 :meth:`~flask.Flask.create_jinja_environment` method instead.386387Version 0.4388-----------389390For application developers there are no changes that require changes in391your code. In case you are developing on a Flask extension however, and392that extension has a unittest-mode you might want to link the activation393of that mode to the new ``TESTING`` flag.394395Version 0.3396-----------397398Flask 0.3 introduces configuration support and logging as well as399categories for flashing messages. All these are features that are 100%400backwards compatible but you might want to take advantage of them.401402Configuration Support403`````````````````````404405The configuration support makes it easier to write any kind of application406that requires some sort of configuration. (Which most likely is the case407for any application out there).408409If you previously had code like this::410411 app.debug = DEBUG412 app.secret_key = SECRET_KEY413414You no longer have to do that, instead you can just load a configuration415into the config object. How this works is outlined in :ref:`config`.416417Logging Integration418```````````````````419420Flask now configures a logger for you with some basic and useful defaults.421If you run your application in production and want to profit from422automatic error logging, you might be interested in attaching a proper log423handler. Also you can start logging warnings and errors into the logger424when appropriately. For more information on that, read425:ref:`application-errors`.426427Categories for Flash Messages428`````````````````````````````429430Flash messages can now have categories attached. This makes it possible431to render errors, warnings or regular messages differently for example.432This is an opt-in feature because it requires some rethinking in the code.433434Read all about that in the :ref:`message-flashing-pattern` pattern.