Skip to content
Myr

upgrading.rst

This file

Path

docs/upgrading.rst

382 lines · 15.9 KiB

Last changed by

Always log now, even if debug is off.Armin Ronacherbefore adoption84ad89f

History of this file

Take it

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

Fixed a documentation typoArmin Ronacherbefore adoptione59e005

lines 1–21why, 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 `easy_install` command to upgrade your Flask18installation, make sure to pass it the ``-U`` parameter::1920 $ easy_install -U Flask21

Always log now, even if debug is off.Armin Ronacherbefore adoption84ad89f

lines 22–31why, one step back
22.. _upgrading-to-10:
2324Version 1.025-----------2627Flask 1.0 removed the ``debug_log_format`` attribute from Flask28applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can29be used to disable the default log handlers and custom log handlers can be30set up.31

Fixed a documentation typoArmin Ronacherbefore adoptione59e005

lines 32–55why, one step back
32.. _upgrading-to-010:
3334Version 0.1035------------3637The biggest change going from 0.9 to 0.10 is that the cookie serialization38format changed from pickle to a specialized JSON format. This change has39been done in order to avoid the damage an attacker can do if the secret40key is leaked. When you upgrade you will notice two major changes: all41sessions that were issued before the upgrade are invalidated and you can42only store a limited amount of types in the session. The new sessions are43by design much more restricted to only allow JSON with a few small44extensions for tuples and strings with HTML markup.4546In order to not break people's sessions it is possible to continue using47the old session system by using the `Flask-OldSessions`_ extension.4849Flask also started storing the :data:`flask.g` object on the application50context instead of the request context. This change should be transparent51for you but it means that you now can store things on the ``g`` object52when there is no request context yet but an application context. The old53``flask.Flask.request_globals_class`` attribute was renamed to54:attr:`flask.Flask.app_ctx_globals_class`.55

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e

line 56why, one step back
56.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/

Fixed a documentation typoArmin Ronacherbefore adoptione59e005

lines 57–76why, one step back
57
58Version 0.959-----------6061The behavior of returning tuples from a function was simplified. If you62return a tuple it no longer defines the arguments for the response object63you're creating, it's now always a tuple in the form ``(response, status,64headers)`` where at least one item has to be provided. If you depend on65the old behavior, you can add it easily by subclassing Flask::6667 class TraditionalFlask(Flask):68 def make_response(self, rv):69 if isinstance(rv, tuple):70 return self.response_class(*rv)71 return Flask.make_response(self, rv)7273If you maintain an extension that was using :data:`~flask._request_ctx_stack`74before, please consider changing to :data:`~flask._app_ctx_stack` if it makes75sense for your extension. For instance, the app context stack makes sense for76extensions which connect to databases. Using the app context stack instead of

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

line 77why, one step back
77the request context stack will make extensions more readily handle use cases

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption6018b12

line 78why, one step back
78outside of requests.

Fixed a documentation typoArmin Ronacherbefore adoptione59e005

lines 79–127why, one step back
79
80Version 0.881-----------8283Flask introduced a new session interface system. We also noticed that84there was a naming collision between `flask.session` the module that85implements sessions and :data:`flask.session` which is the global session86object. With that introduction we moved the implementation details for87the session system into a new module called :mod:`flask.sessions`. If you88used the previously undocumented session support we urge you to upgrade.8990If invalid JSON data was submitted Flask will now raise a91:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the92default :exc:`ValueError` bubble up. This has the advantage that you no93longer have to handle that error to avoid an internal server error showing94up for the user. If you were catching this down explicitly in the past95as `ValueError` you will need to change this.9697Due to a bug in the test client Flask 0.7 did not trigger teardown98handlers when the test client was used in a with statement. This was99since fixed but might require some changes in your testsuites if you100relied on this behavior.101102Version 0.7103-----------104105In Flask 0.7 we cleaned up the code base internally a lot and did some106backwards incompatible changes that make it easier to implement larger107applications with Flask. Because we want to make upgrading as easy as108possible we tried to counter the problems arising from these changes by109providing a script that can ease the transition.110111The script scans your whole application and generates an unified diff with112changes it assumes are safe to apply. However as this is an automated113tool it won't be able to find all use cases and it might miss some. We114internally spread a lot of deprecation warnings all over the place to make115it easy to find pieces of code that it was unable to upgrade.116117We strongly recommend that you hand review the generated patchfile and118only apply the chunks that look good.119120If you are using git as version control system for your project we121recommend applying the patch with ``path -p1 < patchfile.diff`` and then122using the interactive commit feature to only apply the chunks that look123good.124125To apply the upgrade script do the following:1261271. Download the script: `flask-07-upgrade.py

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

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

Fixed a documentation typoArmin Ronacherbefore adoptione59e005

lines 129–382why, one step back
1292. Run it in the directory of your application::
130131 python flask-07-upgrade.py > patchfile.diff1321333. Review the generated patchfile.1344. Apply the patch::135136 patch -p1 < patchfile.diff1371385. If you were using per-module template folders you need to move some139 templates around. Previously if you had a folder named ``templates``140 next to a blueprint named ``admin`` the implicit template path141 automatically was ``admin/index.html`` for a template file called142 ``templates/index.html``. This no longer is the case. Now you need143 to name the template ``templates/admin/index.html``. The tool will144 not detect this so you will have to do that on your own.145146Please note that deprecation warnings are disabled by default starting147with Python 2.7. In order to see the deprecation warnings that might be148emitted you have to enabled them with the :mod:`warnings` module.149150If you are working with windows and you lack the `patch` command line151utility you can get it as part of various Unix runtime environments for152windows including cygwin, msysgit or ming32. Also source control systems153like svn, hg or git have builtin support for applying unified diffs as154generated by the tool. Check the manual of your version control system155for more information.156157Bug in Request Locals158`````````````````````159160Due to a bug in earlier implementations the request local proxies now161raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they162are unbound. If you caught these exceptions with :exc:`AttributeError`163before, you should catch them with :exc:`RuntimeError` now.164165Additionally the :func:`~flask.send_file` function is now issuing166deprecation warnings if you depend on functionality that will be removed167in Flask 1.0. Previously it was possible to use etags and mimetypes168when file objects were passed. This was unreliable and caused issues169for a few setups. If you get a deprecation warning, make sure to170update your application to work with either filenames there or disable171etag attaching and attach them yourself.172173Old code::174175 return send_file(my_file_object)176 return send_file(my_file_object)177178New code::179180 return send_file(my_file_object, add_etags=False)181182.. _upgrading-to-new-teardown-handling:183184Upgrading to new Teardown Handling185``````````````````````````````````186187We streamlined the behavior of the callbacks for request handling. For188things that modify the response the :meth:`~flask.Flask.after_request`189decorators continue to work as expected, but for things that absolutely190must happen at the end of request we introduced the new191:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that192change also made after-request work differently under error conditions.193It's not consistently skipped if exceptions happen whereas previously it194might have been called twice to ensure it is executed at the end of the195request.196197If you have database connection code that looks like this::198199 @app.after_request200 def after_request(response):201 g.db.close()202 return response203204You are now encouraged to use this instead::205206 @app.teardown_request207 def after_request(exception):208 if hasattr(g, 'db'):209 g.db.close()210211On the upside this change greatly improves the internal code flow and212makes it easier to customize the dispatching and error handling. This213makes it now a lot easier to write unit tests as you can prevent closing214down of database connections for a while. You can take advantage of the215fact that the teardown callbacks are called when the response context is216removed from the stack so a test can query the database after request217handling::218219 with app.test_client() as client:220 resp = client.get('/')221 # g.db is still bound if there is such a thing222223 # and here it's gone224225Manual Error Handler Attaching226``````````````````````````````227228While it is still possible to attach error handlers to229:attr:`Flask.error_handlers` it's discouraged to do so and in fact230deprecated. In general we no longer recommend custom error handler231attaching via assignments to the underlying dictionary due to the more232complex internal handling to support arbitrary exception classes and233blueprints. See :meth:`Flask.errorhandler` for more information.234235The proper upgrade is to change this::236237 app.error_handlers[403] = handle_error238239Into this::240241 app.register_error_handler(403, handle_error)242243Alternatively you should just attach the function with a decorator::244245 @app.errorhandler(403)246 def handle_error(e):247 ...248249(Note that :meth:`register_error_handler` is new in Flask 0.7)250251Blueprint Support252`````````````````253254Blueprints replace the previous concept of “Modules” in Flask. They255provide better semantics for various features and work better with large256applications. The update script provided should be able to upgrade your257applications automatically, but there might be some cases where it fails258to upgrade. What changed?259260- Blueprints need explicit names. Modules had an automatic name261 guesssing scheme where the shortname for the module was taken from the262 last part of the import module. The upgrade script tries to guess263 that name but it might fail as this information could change at264 runtime.265- Blueprints have an inverse behavior for :meth:`url_for`. Previously266 ``.foo`` told :meth:`url_for` that it should look for the endpoint267 `foo` on the application. Now it means “relative to current module”.268 The script will inverse all calls to :meth:`url_for` automatically for269 you. It will do this in a very eager way so you might end up with270 some unnecessary leading dots in your code if you're not using271 modules.272- Blueprints do not automatically provide static folders. They will273 also no longer automatically export templates from a folder called274 `templates` next to their location however but it can be enabled from275 the constructor. Same with static files: if you want to continue276 serving static files you need to tell the constructor explicitly the277 path to the static folder (which can be relative to the blueprint's278 module path).279- Rendering templates was simplified. Now the blueprints can provide280 template folders which are added to a general template searchpath.281 This means that you need to add another subfolder with the blueprint's282 name into that folder if you want ``blueprintname/template.html`` as283 the template name.284285If you continue to use the `Module` object which is deprecated, Flask will286restore the previous behavior as good as possible. However we strongly287recommend upgrading to the new blueprints as they provide a lot of useful288improvement such as the ability to attach a blueprint multiple times,289blueprint specific error handlers and a lot more.290291292Version 0.6293-----------294295Flask 0.6 comes with a backwards incompatible change which affects the296order of after-request handlers. Previously they were called in the order297of the registration, now they are called in reverse order. This change298was made so that Flask behaves more like people expected it to work and299how other systems handle request pre- and postprocessing. If you300depend on the order of execution of post-request functions, be sure to301change the order.302303Another change that breaks backwards compatibility is that context304processors will no longer override values passed directly to the template305rendering function. If for example `request` is as variable passed306directly to the template, the default context processor will not override307it with the current request object. This makes it easier to extend308context processors later to inject additional variables without breaking309existing template not expecting them.310311Version 0.5312-----------313314Flask 0.5 is the first release that comes as a Python package instead of a315single module. There were a couple of internal refactoring so if you316depend on undocumented internal details you probably have to adapt the317imports.318319The following changes may be relevant to your application:320321- autoescaping no longer happens for all templates. Instead it is322 configured to only happen on files ending with ``.html``, ``.htm``,323 ``.xml`` and ``.xhtml``. If you have templates with different324 extensions you should override the325 :meth:`~flask.Flask.select_jinja_autoescape` method.326- Flask no longer supports zipped applications in this release. This327 functionality might come back in future releases if there is demand328 for this feature. Removing support for this makes the Flask internal329 code easier to understand and fixes a couple of small issues that make330 debugging harder than necessary.331- The `create_jinja_loader` function is gone. If you want to customize332 the Jinja loader now, use the333 :meth:`~flask.Flask.create_jinja_environment` method instead.334335Version 0.4336-----------337338For application developers there are no changes that require changes in339your code. In case you are developing on a Flask extension however, and340that extension has a unittest-mode you might want to link the activation341of that mode to the new ``TESTING`` flag.342343Version 0.3344-----------345346Flask 0.3 introduces configuration support and logging as well as347categories for flashing messages. All these are features that are 100%348backwards compatible but you might want to take advantage of them.349350Configuration Support351`````````````````````352353The configuration support makes it easier to write any kind of application354that requires some sort of configuration. (Which most likely is the case355for any application out there).356357If you previously had code like this::358359 app.debug = DEBUG360 app.secret_key = SECRET_KEY361362You no longer have to do that, instead you can just load a configuration363into the config object. How this works is outlined in :ref:`config`.364365Logging Integration366```````````````````367368Flask now configures a logger for you with some basic and useful defaults.369If you run your application in production and want to profit from370automatic error logging, you might be interested in attaching a proper log371handler. Also you can start logging warnings and errors into the logger372when appropriately. For more information on that, read373:ref:`application-errors`.374375Categories for Flash Messages376`````````````````````````````377378Flash messages can now have categories attached. This makes it possible379to render errors, warnings or regular messages differently for example.380This is an opt-in feature because it requires some rethinking in the code.381382Read all about that in the :ref:`message-flashing-pattern` pattern.