upgrading.rst
This file
Path
docs/upgrading.rst
324 lines · 13.4 KiB
Last changed by
The test client now properly pops response contexts on __exit__Armin Ronacherbefore adoptiond49221b
History of this fileTake it
The walk stopped after 200 commits: lines older than 0fb2e4c point at it.
More invalid doc fixingArmin Ronacherbefore adoption0fb2e4c
lines 1–21why, one step back1Upgrading 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 Flask21Backwards compatibility importArmin Ronacherbefore adoptionf29ec35
lines 22–31why, one step back22Version 0.823-----------2425Flask introduced a new session interface system. We also noticed that26there was a naming collision between `flask.session` the module that27implements sessions and :data:`flask.session` which is the global session28object. With that introduction we moved the implementation details for29the session system into a new module called :mod:`flask.sessions`. If you30used the previously undocumented session support we urge you to upgrade.31If JSON parsing fails it now issues a BadRequest exception.Armin Ronacherbefore adoptionce70131
lines 32–38why, one step back32If invalid JSON data was submitted Flask will now raise a33:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the34default :exc:`ValueError` bubble up. This has the advantage that you no35longer have to handle that error to avoid an internal server error showing36up for the user. If you were catching this down explicitly in the past37as `ValueError` you will need to change this.38The test client now properly pops response contexts on __exit__Armin Ronacherbefore adoptiond49221b
lines 39–43why, one step back39Due to a bug in the test client Flask 0.7 did not trigger teardown40handlers when the test client was used in a with statement. This was41since fixed but might require some changes in your testsuites if you42relied on this behavior.43More invalid doc fixingArmin Ronacherbefore adoption0fb2e4c
lines 44–149why, one step back44Version 0.745-----------4647In Flask 0.7 we cleaned up the code base internally a lot and did some48backwards incompatible changes that make it easier to implement larger49applications with Flask. Because we want to make upgrading as easy as50possible we tried to counter the problems arising from these changes by51providing a script that can ease the transition.5253The script scans your whole application and generates an unified diff with54changes it assumes are safe to apply. However as this is an automated55tool it won't be able to find all use cases and it might miss some. We56internally spread a lot of deprecation warnings all over the place to make57it easy to find pieces of code that it was unable to upgrade.5859We strongly recommend that you hand review the generated patchfile and60only apply the chunks that look good.6162If you are using git as version control system for your project we63recommend applying the patch with ``path -p1 < patchfile.diff`` and then64using the interactive commit feature to only apply the chunks that look65good.6667To apply the upgrade script do the following:68691. Download the script: `flask-07-upgrade.py70 <https://raw.github.com/mitsuhiko/flask/master/scripts/flask-07-upgrade.py>`_712. Run it in the directory of your application::7273 python flask-07-upgrade.py > patchfile.diff74753. Review the generated patchfile.764. Apply the patch::7778 patch -p1 < patchfile.diff79805. If you were using per-module template folders you need to move some81 templates around. Previously if you had a folder named ``templates``82 next to a blueprint named ``admin`` the implicit template path83 automatically was ``admin/index.html`` for a template file called84 ``templates/index.html``. This no longer is the case. Now you need85 to name the template ``templates/admin/index.html``. The tool will86 not detect this so you will have to do that on your own.8788Please note that deprecation warnings are disabled by default starting89with Python 2.7. In order to see the deprecation warnings that might be90emitted you have to enabled them with the :mod:`warnings` module.9192If you are working with windows and you lack the `patch` command line93utility you can get it as part of various Unix runtime environments for94windows including cygwin, msysgit or ming32. Also source control systems95like svn, hg or git have builtin support for applying unified diffs as96generated by the tool. Check the manual of your version control system97for more information.9899Bug in Request Locals100`````````````````````101102Due to a bug in earlier implementations the request local proxies now103raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they104are unbound. If you caught these exceptions with :exc:`AttributeError`105before, you should catch them with :exc:`RuntimeError` now.106107Additionally the :func:`~flask.send_file` function is now issuing108deprecation warnings if you depend on functionality that will be removed109in Flask 1.0. Previously it was possible to use etags and mimetypes110when file objects were passed. This was unreliable and caused issues111for a few setups. If you get a deprecation warning, make sure to112update your application to work with either filenames there or disable113etag attaching and attach them yourself.114115Old code::116117 return send_file(my_file_object)118 return send_file(my_file_object)119120New code::121122 return send_file(my_file_object, add_etags=False)123124.. _upgrading-to-new-teardown-handling:125126Upgrading to new Teardown Handling127``````````````````````````````````128129We streamlined the behavior of the callbacks for request handling. For130things that modify the response the :meth:`~flask.Flask.after_request`131decorators continue to work as expected, but for things that absolutely132must happen at the end of request we introduced the new133:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that134change also made after-request work differently under error conditions.135It's not consistently skipped if exceptions happen whereas previously it136might have been called twice to ensure it is executed at the end of the137request.138139If you have database connection code that looks like this::140141 @app.after_request142 def after_request(response):143 g.db.close()144 return response145146You are now encouraged to use this instead::147148 @app.teardown_request149 def after_request(exception):Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551
lines 150–151why, one step back150 if hasattr(g, 'db'):151 g.db.close()More invalid doc fixingArmin Ronacherbefore adoption0fb2e4c
lines 152–324why, one step back152153On the upside this change greatly improves the internal code flow and154makes it easier to customize the dispatching and error handling. This155makes it now a lot easier to write unit tests as you can prevent closing156down of database connections for a while. You can take advantage of the157fact that the teardown callbacks are called when the response context is158removed from the stack so a test can query the database after request159handling::160161 with app.test_client() as client:162 resp = client.get('/')163 # g.db is still bound if there is such a thing164165 # and here it's gone166167Manual Error Handler Attaching168``````````````````````````````169170While it is still possible to attach error handlers to171:attr:`Flask.error_handlers` it's discouraged to do so and in fact172deprecated. In generaly we no longer recommend custom error handler173attaching via assignments to the underlying dictionary due to the more174complex internal handling to support arbitrary exception classes and175blueprints. See :meth:`Flask.errorhandler` for more information.176177The proper upgrade is to change this::178179 app.error_handlers[403] = handle_error180181Into this::182183 app.register_error_handler(403, handle_error)184185Alternatively you should just attach the function with a decorator::186187 @app.errorhandler(403)188 def handle_error(e):189 ...190191(Note that :meth:`register_error_handler` is new in Flask 0.7)192193Blueprint Support194`````````````````195196Blueprints replace the previous concept of “Modules” in Flask. They197provide better semantics for various features and work better with large198applications. The update script provided should be able to upgrade your199applications automatically, but there might be some cases where it fails200to upgrade. What changed?201202- Blueprints need explicit names. Modules had an automatic name203 guesssing scheme where the shortname for the module was taken from the204 last part of the import module. The upgrade script tries to guess205 that name but it might fail as this information could change at206 runtime.207- Blueprints have an inverse behavior for :meth:`url_for`. Previously208 ``.foo`` told :meth:`url_for` that it should look for the endpoint209 `foo` on the application. Now it means “relative to current module”.210 The script will inverse all calls to :meth:`url_for` automatically for211 you. It will do this in a very eager way so you might end up with212 some unnecessary leading dots in your code if you're not using213 modules.214- Blueprints do not automatically provide static folders. They will215 also no longer automatically export templates from a folder called216 `templates` next to their location however but it can be enabled from217 the constructor. Same with static files: if you want to continue218 serving static files you need to tell the constructor explicitly the219 path to the static folder (which can be relative to the blueprint's220 module path).221- Rendering templates was simplified. Now the blueprints can provide222 template folders which are added to a general template searchpath.223 This means that you need to add another subfolder with the blueprint's224 name into that folder if you want ``blueprintname/template.html`` as225 the template name.226227If you continue to use the `Module` object which is deprecated, Flask will228restore the previous behavior as good as possible. However we strongly229recommend upgrading to the new blueprints as they provide a lot of useful230improvement such as the ability to attach a blueprint multiple times,231blueprint specific error handlers and a lot more.232233234Version 0.6235-----------236237Flask 0.6 comes with a backwards incompatible change which affects the238order of after-request handlers. Previously they were called in the order239of the registration, now they are called in reverse order. This change240was made so that Flask behaves more like people expected it to work and241how other systems handle request pre- and postprocessing. If you242depend on the order of execution of post-request functions, be sure to243change the order.244245Another change that breaks backwards compatibility is that context246processors will no longer override values passed directly to the template247rendering function. If for example `request` is as variable passed248directly to the template, the default context processor will not override249it with the current request object. This makes it easier to extend250context processors later to inject additional variables without breaking251existing template not expecting them.252253Version 0.5254-----------255256Flask 0.5 is the first release that comes as a Python package instead of a257single module. There were a couple of internal refactoring so if you258depend on undocumented internal details you probably have to adapt the259imports.260261The following changes may be relevant to your application:262263- autoescaping no longer happens for all templates. Instead it is264 configured to only happen on files ending with ``.html``, ``.htm``,265 ``.xml`` and ``.xhtml``. If you have templates with different266 extensions you should override the267 :meth:`~flask.Flask.select_jinja_autoescape` method.268- Flask no longer supports zipped applications in this release. This269 functionality might come back in future releases if there is demand270 for this feature. Removing support for this makes the Flask internal271 code easier to understand and fixes a couple of small issues that make272 debugging harder than necessary.273- The `create_jinja_loader` function is gone. If you want to customize274 the Jinja loader now, use the275 :meth:`~flask.Flask.create_jinja_environment` method instead.276277Version 0.4278-----------279280For application developers there are no changes that require changes in281your code. In case you are developing on a Flask extension however, and282that extension has a unittest-mode you might want to link the activation283of that mode to the new ``TESTING`` flag.284285Version 0.3286-----------287288Flask 0.3 introduces configuration support and logging as well as289categories for flashing messages. All these are features that are 100%290backwards compatible but you might want to take advantage of them.291292Configuration Support293`````````````````````294295The configuration support makes it easier to write any kind of application296that requires some sort of configuration. (Which most likely is the case297for any application out there).298299If you previously had code like this::300301 app.debug = DEBUG302 app.secret_key = SECRET_KEY303304You no longer have to do that, instead you can just load a configuration305into the config object. How this works is outlined in :ref:`config`.306307Logging Integration308```````````````````309310Flask now configures a logger for you with some basic and useful defaults.311If you run your application in production and want to profit from312automatic error logging, you might be interested in attaching a proper log313handler. Also you can start logging warnings and errors into the logger314when appropriately. For more information on that, read315:ref:`application-errors`.316317Categories for Flash Messages318`````````````````````````````319320Flash messages can now have categories attached. This makes it possible321to render errors, warnings or regular messages differently for example.322This is an opt-in feature because it requires some rethinking in the code.323324Read all about that in the :ref:`message-flashing-pattern` pattern.