Skip to content
Myr

upgrading.rst

This file

Path

docs/upgrading.rst

403 lines · 16.9 KiB

Last changed by

Merge branch 'alanhamlett-master'Markus Unterwaditzerbefore adoptiondb09c67

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 :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: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.3132The behavior of error handlers was changed.33The precedence of handlers used to be based on the decoration/call order of34:meth:`~flask.Flask.errorhandler` and35:meth:`~flask.Flask.register_error_handler`, respectively.36Now the inheritance hierarchy takes precedence and handlers for more37specific exception classes are executed instead of more general ones.38See :ref:`error-handlers` for specifics.3940The :func:`~flask.templating.render_template_string` function has changed to41autoescape template variables by default. This better matches the behavior42of :func:`~flask.templating.render_template`.4344.. note::4546    There used to be a logic error allowing you to register handlers47    only for exception *instances*. This was unintended and plain wrong,48    and therefore was replaced with the intended behavior of registering49    handlers only using exception classes and HTTP error codes.50    51    Trying to register a handler on an instance now raises :exc:`ValueError`.5253.. _upgrading-to-010:5455Version 0.1056------------5758The biggest change going from 0.9 to 0.10 is that the cookie serialization59format changed from pickle to a specialized JSON format.  This change has60been done in order to avoid the damage an attacker can do if the secret61key is leaked.  When you upgrade you will notice two major changes: all62sessions that were issued before the upgrade are invalidated and you can63only store a limited amount of types in the session.  The new sessions are64by design much more restricted to only allow JSON with a few small65extensions for tuples and strings with HTML markup.6667In order to not break people's sessions it is possible to continue using68the old session system by using the `Flask-OldSessions`_ extension.6970Flask also started storing the :data:`flask.g` object on the application71context instead of the request context.  This change should be transparent72for you but it means that you now can store things on the ``g`` object73when there is no request context yet but an application context.  The old74``flask.Flask.request_globals_class`` attribute was renamed to75:attr:`flask.Flask.app_ctx_globals_class`.7677.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/7879Version 0.980-----------8182The behavior of returning tuples from a function was simplified.  If you83return a tuple it no longer defines the arguments for the response object84you're creating, it's now always a tuple in the form ``(response, status,85headers)`` where at least one item has to be provided.  If you depend on86the old behavior, you can add it easily by subclassing Flask::8788    class TraditionalFlask(Flask):89        def make_response(self, rv):90            if isinstance(rv, tuple):91                return self.response_class(*rv)92            return Flask.make_response(self, rv)9394If you maintain an extension that was using :data:`~flask._request_ctx_stack`95before, please consider changing to :data:`~flask._app_ctx_stack` if it makes96sense for your extension.  For instance, the app context stack makes sense for97extensions which connect to databases.  Using the app context stack instead of98the request context stack will make extensions more readily handle use cases99outside of requests.100101Version 0.8102-----------103104Flask introduced a new session interface system.  We also noticed that105there was a naming collision between `flask.session` the module that106implements sessions and :data:`flask.session` which is the global session107object.  With that introduction we moved the implementation details for108the session system into a new module called :mod:`flask.sessions`.  If you109used the previously undocumented session support we urge you to upgrade.110111If invalid JSON data was submitted Flask will now raise a112:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the113default :exc:`ValueError` bubble up.  This has the advantage that you no114longer have to handle that error to avoid an internal server error showing115up for the user.  If you were catching this down explicitly in the past116as :exc:`ValueError` you will need to change this.117118Due to a bug in the test client Flask 0.7 did not trigger teardown119handlers when the test client was used in a with statement.  This was120since fixed but might require some changes in your test suites if you121relied on this behavior.122123Version 0.7124-----------125126In Flask 0.7 we cleaned up the code base internally a lot and did some127backwards incompatible changes that make it easier to implement larger128applications with Flask.  Because we want to make upgrading as easy as129possible we tried to counter the problems arising from these changes by130providing a script that can ease the transition.131132The script scans your whole application and generates an unified diff with133changes it assumes are safe to apply.  However as this is an automated134tool it won't be able to find all use cases and it might miss some.  We135internally spread a lot of deprecation warnings all over the place to make136it easy to find pieces of code that it was unable to upgrade.137138We strongly recommend that you hand review the generated patchfile and139only apply the chunks that look good.140141If you are using git as version control system for your project we142recommend applying the patch with ``path -p1 < patchfile.diff`` and then143using the interactive commit feature to only apply the chunks that look144good.145146To apply the upgrade script do the following:1471481.  Download the script: `flask-07-upgrade.py149    <https://raw.githubusercontent.com/mitsuhiko/flask/master/scripts/flask-07-upgrade.py>`_1502.  Run it in the directory of your application::151152        python flask-07-upgrade.py > patchfile.diff1531543.  Review the generated patchfile.1554.  Apply the patch::156157        patch -p1 < patchfile.diff1581595.  If you were using per-module template folders you need to move some160    templates around.  Previously if you had a folder named :file:`templates`161    next to a blueprint named ``admin`` the implicit template path162    automatically was :file:`admin/index.html` for a template file called163    :file:`templates/index.html`.  This no longer is the case.  Now you need164    to name the template :file:`templates/admin/index.html`.  The tool will165    not detect this so you will have to do that on your own.166167Please note that deprecation warnings are disabled by default starting168with Python 2.7.  In order to see the deprecation warnings that might be169emitted you have to enabled them with the :mod:`warnings` module.170171If you are working with windows and you lack the `patch` command line172utility you can get it as part of various Unix runtime environments for173windows including cygwin, msysgit or ming32.  Also source control systems174like svn, hg or git have builtin support for applying unified diffs as175generated by the tool.  Check the manual of your version control system176for more information.177178Bug in Request Locals179`````````````````````180181Due to a bug in earlier implementations the request local proxies now182raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they183are unbound.  If you caught these exceptions with :exc:`AttributeError`184before, you should catch them with :exc:`RuntimeError` now.185186Additionally the :func:`~flask.send_file` function is now issuing187deprecation warnings if you depend on functionality that will be removed188in Flask 1.0.  Previously it was possible to use etags and mimetypes189when file objects were passed.  This was unreliable and caused issues190for a few setups.  If you get a deprecation warning, make sure to191update your application to work with either filenames there or disable192etag attaching and attach them yourself.193194Old code::195196    return send_file(my_file_object)197    return send_file(my_file_object)198199New code::200201    return send_file(my_file_object, add_etags=False)202203.. _upgrading-to-new-teardown-handling:204205Upgrading to new Teardown Handling206``````````````````````````````````207208We streamlined the behavior of the callbacks for request handling.  For209things that modify the response the :meth:`~flask.Flask.after_request`210decorators continue to work as expected, but for things that absolutely211must happen at the end of request we introduced the new212:meth:`~flask.Flask.teardown_request` decorator.  Unfortunately that213change also made after-request work differently under error conditions.214It's not consistently skipped if exceptions happen whereas previously it215might have been called twice to ensure it is executed at the end of the216request.217218If you have database connection code that looks like this::219220    @app.after_request221    def after_request(response):222        g.db.close()223        return response224225You are now encouraged to use this instead::226227    @app.teardown_request228    def after_request(exception):229        if hasattr(g, 'db'):230            g.db.close()231232On the upside this change greatly improves the internal code flow and233makes it easier to customize the dispatching and error handling.  This234makes it now a lot easier to write unit tests as you can prevent closing235down of database connections for a while.  You can take advantage of the236fact that the teardown callbacks are called when the response context is237removed from the stack so a test can query the database after request238handling::239240    with app.test_client() as client:241        resp = client.get('/')242        # g.db is still bound if there is such a thing243244    # and here it's gone245246Manual Error Handler Attaching247``````````````````````````````248249While it is still possible to attach error handlers to250:attr:`Flask.error_handlers` it's discouraged to do so and in fact251deprecated.  In general we no longer recommend custom error handler252attaching via assignments to the underlying dictionary due to the more253complex internal handling to support arbitrary exception classes and254blueprints.  See :meth:`Flask.errorhandler` for more information.255256The proper upgrade is to change this::257258    app.error_handlers[403] = handle_error259260Into this::261262    app.register_error_handler(403, handle_error)263264Alternatively you should just attach the function with a decorator::265266    @app.errorhandler(403)267    def handle_error(e):268        ...269270(Note that :meth:`register_error_handler` is new in Flask 0.7)271272Blueprint Support273`````````````````274275Blueprints replace the previous concept of “Modules” in Flask.  They276provide better semantics for various features and work better with large277applications.  The update script provided should be able to upgrade your278applications automatically, but there might be some cases where it fails279to upgrade.  What changed?280281-   Blueprints need explicit names.  Modules had an automatic name282    guessing scheme where the shortname for the module was taken from the283    last part of the import module.  The upgrade script tries to guess284    that name but it might fail as this information could change at285    runtime.286-   Blueprints have an inverse behavior for :meth:`url_for`.  Previously287    ``.foo`` told :meth:`url_for` that it should look for the endpoint288    `foo` on the application.  Now it means “relative to current module”.289    The script will inverse all calls to :meth:`url_for` automatically for290    you.  It will do this in a very eager way so you might end up with291    some unnecessary leading dots in your code if you're not using292    modules.293-   Blueprints do not automatically provide static folders.  They will294    also no longer automatically export templates from a folder called295    :file:`templates` next to their location however but it can be enabled from296    the constructor.  Same with static files: if you want to continue297    serving static files you need to tell the constructor explicitly the298    path to the static folder (which can be relative to the blueprint's299    module path).300-   Rendering templates was simplified.  Now the blueprints can provide301    template folders which are added to a general template searchpath.302    This means that you need to add another subfolder with the blueprint's303    name into that folder if you want :file:`blueprintname/template.html` as304    the template name.305306If you continue to use the `Module` object which is deprecated, Flask will307restore the previous behavior as good as possible.  However we strongly308recommend upgrading to the new blueprints as they provide a lot of useful309improvement such as the ability to attach a blueprint multiple times,310blueprint specific error handlers and a lot more.311312313Version 0.6314-----------315316Flask 0.6 comes with a backwards incompatible change which affects the317order of after-request handlers.  Previously they were called in the order318of the registration, now they are called in reverse order.  This change319was made so that Flask behaves more like people expected it to work and320how other systems handle request pre- and post-processing.  If you321depend on the order of execution of post-request functions, be sure to322change the order.323324Another change that breaks backwards compatibility is that context325processors will no longer override values passed directly to the template326rendering function.  If for example `request` is as variable passed327directly to the template, the default context processor will not override328it with the current request object.  This makes it easier to extend329context processors later to inject additional variables without breaking330existing template not expecting them.331332Version 0.5333-----------334335Flask 0.5 is the first release that comes as a Python package instead of a336single module.  There were a couple of internal refactoring so if you337depend on undocumented internal details you probably have to adapt the338imports.339340The following changes may be relevant to your application:341342-   autoescaping no longer happens for all templates.  Instead it is343    configured to only happen on files ending with ``.html``, ``.htm``,344    ``.xml`` and ``.xhtml``.  If you have templates with different345    extensions you should override the346    :meth:`~flask.Flask.select_jinja_autoescape` method.347-   Flask no longer supports zipped applications in this release.  This348    functionality might come back in future releases if there is demand349    for this feature.  Removing support for this makes the Flask internal350    code easier to understand and fixes a couple of small issues that make351    debugging harder than necessary.352-   The `create_jinja_loader` function is gone.  If you want to customize353    the Jinja loader now, use the354    :meth:`~flask.Flask.create_jinja_environment` method instead.355356Version 0.4357-----------358359For application developers there are no changes that require changes in360your code.  In case you are developing on a Flask extension however, and361that extension has a unittest-mode you might want to link the activation362of that mode to the new ``TESTING`` flag.363364Version 0.3365-----------366367Flask 0.3 introduces configuration support and logging as well as368categories for flashing messages.  All these are features that are 100%369backwards compatible but you might want to take advantage of them.370371Configuration Support372`````````````````````373374The configuration support makes it easier to write any kind of application375that requires some sort of configuration.  (Which most likely is the case376for any application out there).377378If you previously had code like this::379380    app.debug = DEBUG381    app.secret_key = SECRET_KEY382383You no longer have to do that, instead you can just load a configuration384into the config object.  How this works is outlined in :ref:`config`.385386Logging Integration387```````````````````388389Flask now configures a logger for you with some basic and useful defaults.390If you run your application in production and want to profit from391automatic error logging, you might be interested in attaching a proper log392handler.  Also you can start logging warnings and errors into the logger393when appropriately.  For more information on that, read394:ref:`application-errors`.395396Categories for Flash Messages397`````````````````````````````398399Flash messages can now have categories attached.  This makes it possible400to render errors, warnings or regular messages differently for example.401This is an opt-in feature because it requires some rethinking in the code.402403Read all about that in the :ref:`message-flashing-pattern` pattern.