Skip to content
Myr

upgrading.rst

This file

Path

docs/upgrading.rst

372 lines · 15.6 KiB

Last changed by

Fixed a broken link in the docsArmin Ronacherbefore adoptionfc2225b

History of this file

Take it

1Upgrading to Newer Releases2===========================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 Flask2122.. _upgrading-to-010:2324Version 0.1025------------2627The biggest change going from 0.9 to 0.10 is that the cookie serialization28format changed from pickle to a specialized JSON format.  This change has29been done in order to avoid the damage an attacker can do if the secret30key is leaked.  When you upgrade you will notice two major changes: all31sessions that were issued before the upgrade are invalidated and you can32only store a limited amount of types in the session.  The new sessions are33by design much more restricted to only allow JSON with a few small34extensions for tuples and strings with HTML markup.3536In order to not break people's sessions it is possible to continue using37the old session system by using the `Flask-OldSessions`_ extension.3839Flask also started storing the :data:`flask.g` object on the application40context instead of the request context.  This change should be transparent41for you but it means that you now can store things on the ``g`` object42when there is no request context yet but an application context.  The old43``flask.Flask.request_globals_class`` attribute was renamed to44:attr:`flask.Flask.app_ctx_globals_class`.4546.. _Flask-OldSessions: http://packages.python.org/Flask-OldSessions/4748Version 0.949-----------5051The behavior of returning tuples from a function was simplified.  If you52return a tuple it no longer defines the arguments for the response object53you're creating, it's now always a tuple in the form ``(response, status,54headers)`` where at least one item has to be provided.  If you depend on55the old behavior, you can add it easily by subclassing Flask::5657    class TraditionalFlask(Flask):58        def make_response(self, rv):59            if isinstance(rv, tuple):60                return self.response_class(*rv)61            return Flask.make_response(self, rv)6263If you maintain an extension that was using :data:`~flask._request_ctx_stack`64before, please consider changing to :data:`~flask._app_ctx_stack` if it makes65sense for your extension.  For instance, the app context stack makes sense for66extensions which connect to databases.  Using the app context stack instead of67the request stack will make extensions more readily handle use cases outside of68requests.6970Version 0.871-----------7273Flask introduced a new session interface system.  We also noticed that74there was a naming collision between `flask.session` the module that75implements sessions and :data:`flask.session` which is the global session76object.  With that introduction we moved the implementation details for77the session system into a new module called :mod:`flask.sessions`.  If you78used the previously undocumented session support we urge you to upgrade.7980If invalid JSON data was submitted Flask will now raise a81:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the82default :exc:`ValueError` bubble up.  This has the advantage that you no83longer have to handle that error to avoid an internal server error showing84up for the user.  If you were catching this down explicitly in the past85as `ValueError` you will need to change this.8687Due to a bug in the test client Flask 0.7 did not trigger teardown88handlers when the test client was used in a with statement.  This was89since fixed but might require some changes in your testsuites if you90relied on this behavior.9192Version 0.793-----------9495In Flask 0.7 we cleaned up the code base internally a lot and did some96backwards incompatible changes that make it easier to implement larger97applications with Flask.  Because we want to make upgrading as easy as98possible we tried to counter the problems arising from these changes by99providing a script that can ease the transition.100101The script scans your whole application and generates an unified diff with102changes it assumes are safe to apply.  However as this is an automated103tool it won't be able to find all use cases and it might miss some.  We104internally spread a lot of deprecation warnings all over the place to make105it easy to find pieces of code that it was unable to upgrade.106107We strongly recommend that you hand review the generated patchfile and108only apply the chunks that look good.109110If you are using git as version control system for your project we111recommend applying the patch with ``path -p1 < patchfile.diff`` and then112using the interactive commit feature to only apply the chunks that look113good.114115To apply the upgrade script do the following:1161171.  Download the script: `flask-07-upgrade.py118    <https://raw.github.com/mitsuhiko/flask/master/scripts/flask-07-upgrade.py>`_1192.  Run it in the directory of your application::120121        python flask-07-upgrade.py > patchfile.diff1221233.  Review the generated patchfile.1244.  Apply the patch::125126        patch -p1 < patchfile.diff1271285.  If you were using per-module template folders you need to move some129    templates around.  Previously if you had a folder named ``templates``130    next to a blueprint named ``admin`` the implicit template path131    automatically was ``admin/index.html`` for a template file called132    ``templates/index.html``.  This no longer is the case.  Now you need133    to name the template ``templates/admin/index.html``.  The tool will134    not detect this so you will have to do that on your own.135136Please note that deprecation warnings are disabled by default starting137with Python 2.7.  In order to see the deprecation warnings that might be138emitted you have to enabled them with the :mod:`warnings` module.139140If you are working with windows and you lack the `patch` command line141utility you can get it as part of various Unix runtime environments for142windows including cygwin, msysgit or ming32.  Also source control systems143like svn, hg or git have builtin support for applying unified diffs as144generated by the tool.  Check the manual of your version control system145for more information.146147Bug in Request Locals148`````````````````````149150Due to a bug in earlier implementations the request local proxies now151raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they152are unbound.  If you caught these exceptions with :exc:`AttributeError`153before, you should catch them with :exc:`RuntimeError` now.154155Additionally the :func:`~flask.send_file` function is now issuing156deprecation warnings if you depend on functionality that will be removed157in Flask 1.0.  Previously it was possible to use etags and mimetypes158when file objects were passed.  This was unreliable and caused issues159for a few setups.  If you get a deprecation warning, make sure to160update your application to work with either filenames there or disable161etag attaching and attach them yourself.162163Old code::164165    return send_file(my_file_object)166    return send_file(my_file_object)167168New code::169170    return send_file(my_file_object, add_etags=False)171172.. _upgrading-to-new-teardown-handling:173174Upgrading to new Teardown Handling175``````````````````````````````````176177We streamlined the behavior of the callbacks for request handling.  For178things that modify the response the :meth:`~flask.Flask.after_request`179decorators continue to work as expected, but for things that absolutely180must happen at the end of request we introduced the new181:meth:`~flask.Flask.teardown_request` decorator.  Unfortunately that182change also made after-request work differently under error conditions.183It's not consistently skipped if exceptions happen whereas previously it184might have been called twice to ensure it is executed at the end of the185request.186187If you have database connection code that looks like this::188189    @app.after_request190    def after_request(response):191        g.db.close()192        return response193194You are now encouraged to use this instead::195196    @app.teardown_request197    def after_request(exception):198        if hasattr(g, 'db'):199            g.db.close()200201On the upside this change greatly improves the internal code flow and202makes it easier to customize the dispatching and error handling.  This203makes it now a lot easier to write unit tests as you can prevent closing204down of database connections for a while.  You can take advantage of the205fact that the teardown callbacks are called when the response context is206removed from the stack so a test can query the database after request207handling::208209    with app.test_client() as client:210        resp = client.get('/')211        # g.db is still bound if there is such a thing212213    # and here it's gone214215Manual Error Handler Attaching216``````````````````````````````217218While it is still possible to attach error handlers to219:attr:`Flask.error_handlers` it's discouraged to do so and in fact220deprecated.  In general we no longer recommend custom error handler221attaching via assignments to the underlying dictionary due to the more222complex internal handling to support arbitrary exception classes and223blueprints.  See :meth:`Flask.errorhandler` for more information.224225The proper upgrade is to change this::226227    app.error_handlers[403] = handle_error228229Into this::230231    app.register_error_handler(403, handle_error)232233Alternatively you should just attach the function with a decorator::234235    @app.errorhandler(403)236    def handle_error(e):237        ...238239(Note that :meth:`register_error_handler` is new in Flask 0.7)240241Blueprint Support242`````````````````243244Blueprints replace the previous concept of “Modules” in Flask.  They245provide better semantics for various features and work better with large246applications.  The update script provided should be able to upgrade your247applications automatically, but there might be some cases where it fails248to upgrade.  What changed?249250-   Blueprints need explicit names.  Modules had an automatic name251    guesssing scheme where the shortname for the module was taken from the252    last part of the import module.  The upgrade script tries to guess253    that name but it might fail as this information could change at254    runtime.255-   Blueprints have an inverse behavior for :meth:`url_for`.  Previously256    ``.foo`` told :meth:`url_for` that it should look for the endpoint257    `foo` on the application.  Now it means “relative to current module”.258    The script will inverse all calls to :meth:`url_for` automatically for259    you.  It will do this in a very eager way so you might end up with260    some unnecessary leading dots in your code if you're not using261    modules.262-   Blueprints do not automatically provide static folders.  They will263    also no longer automatically export templates from a folder called264    `templates` next to their location however but it can be enabled from265    the constructor.  Same with static files: if you want to continue266    serving static files you need to tell the constructor explicitly the267    path to the static folder (which can be relative to the blueprint's268    module path).269-   Rendering templates was simplified.  Now the blueprints can provide270    template folders which are added to a general template searchpath.271    This means that you need to add another subfolder with the blueprint's272    name into that folder if you want ``blueprintname/template.html`` as273    the template name.274275If you continue to use the `Module` object which is deprecated, Flask will276restore the previous behavior as good as possible.  However we strongly277recommend upgrading to the new blueprints as they provide a lot of useful278improvement such as the ability to attach a blueprint multiple times,279blueprint specific error handlers and a lot more.280281282Version 0.6283-----------284285Flask 0.6 comes with a backwards incompatible change which affects the286order of after-request handlers.  Previously they were called in the order287of the registration, now they are called in reverse order.  This change288was made so that Flask behaves more like people expected it to work and289how other systems handle request pre- and postprocessing.  If you290depend on the order of execution of post-request functions, be sure to291change the order.292293Another change that breaks backwards compatibility is that context294processors will no longer override values passed directly to the template295rendering function.  If for example `request` is as variable passed296directly to the template, the default context processor will not override297it with the current request object.  This makes it easier to extend298context processors later to inject additional variables without breaking299existing template not expecting them.300301Version 0.5302-----------303304Flask 0.5 is the first release that comes as a Python package instead of a305single module.  There were a couple of internal refactoring so if you306depend on undocumented internal details you probably have to adapt the307imports.308309The following changes may be relevant to your application:310311-   autoescaping no longer happens for all templates.  Instead it is312    configured to only happen on files ending with ``.html``, ``.htm``,313    ``.xml`` and ``.xhtml``.  If you have templates with different314    extensions you should override the315    :meth:`~flask.Flask.select_jinja_autoescape` method.316-   Flask no longer supports zipped applications in this release.  This317    functionality might come back in future releases if there is demand318    for this feature.  Removing support for this makes the Flask internal319    code easier to understand and fixes a couple of small issues that make320    debugging harder than necessary.321-   The `create_jinja_loader` function is gone.  If you want to customize322    the Jinja loader now, use the323    :meth:`~flask.Flask.create_jinja_environment` method instead.324325Version 0.4326-----------327328For application developers there are no changes that require changes in329your code.  In case you are developing on a Flask extension however, and330that extension has a unittest-mode you might want to link the activation331of that mode to the new ``TESTING`` flag.332333Version 0.3334-----------335336Flask 0.3 introduces configuration support and logging as well as337categories for flashing messages.  All these are features that are 100%338backwards compatible but you might want to take advantage of them.339340Configuration Support341`````````````````````342343The configuration support makes it easier to write any kind of application344that requires some sort of configuration.  (Which most likely is the case345for any application out there).346347If you previously had code like this::348349    app.debug = DEBUG350    app.secret_key = SECRET_KEY351352You no longer have to do that, instead you can just load a configuration353into the config object.  How this works is outlined in :ref:`config`.354355Logging Integration356```````````````````357358Flask now configures a logger for you with some basic and useful defaults.359If you run your application in production and want to profit from360automatic error logging, you might be interested in attaching a proper log361handler.  Also you can start logging warnings and errors into the logger362when appropriately.  For more information on that, read363:ref:`application-errors`.364365Categories for Flash Messages366`````````````````````````````367368Flash messages can now have categories attached.  This makes it possible369to render errors, warnings or regular messages differently for example.370This is an opt-in feature because it requires some rethinking in the code.371372Read all about that in the :ref:`message-flashing-pattern` pattern.