Skip to content
Myr

remove Python 2 from docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 96b4dca · Browse files · 17 files+53 added−908 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+53 added−908 removed

  • other:+53 added−908 removed

17 files+53 added−908 removed

modified:docs/deploying/mod_wsgi.rst-5 removed
209 unmodified lines
210211Add the following lines to the top of your ``.wsgi`` file::212213 activate_this = '/path/to/env/bin/activate_this.py'214 execfile(activate_this, dict(__file__=activate_this))215216For Python 3 add the following lines to the top of your ``.wsgi`` file::217218 activate_this = '/path/to/env/bin/activate_this.py'214 with open(activate_this) as file_:215 exec(file_.read(), dict(__file__=activate_this))216217This sets up the load paths according to the settings of the virtual
1 unmodified line
modified:docs/patterns/distribute.rst-4 removed
17 unmodified lines
18 declare an "entry point" that another package can hook into to extend the19 other package.20- **installation manager**: :command:`pip` can install other libraries for you.2122If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org,23you will already have pip and setuptools on your system. Otherwise, you24will need to install them yourself.2522Flask itself, and all the libraries you can find on PyPI are distributed with23either setuptools or distutils.2425In this case we assume your application is called
148 unmodified lines
modified:docs/patterns/sqlalchemy.rst+3 added-3 removed
37 unmodified lines
38 from sqlalchemy import create_engine39 from sqlalchemy.orm import scoped_session, sessionmaker40 from sqlalchemy.ext.declarative import declarative_base4142 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)42 engine = create_engine('sqlite:////tmp/test.db')43 db_session = scoped_session(sessionmaker(autocommit=False,44 autoflush=False,45 bind=engine))46 Base = declarative_base()
79 unmodified lines
126127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129130 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)130 engine = create_engine('sqlite:////tmp/test.db')131 metadata = MetaData()132 db_session = scoped_session(sessionmaker(autocommit=False,133 autoflush=False,134 bind=engine))
43 unmodified lines
178you basically only need the engine::179180 from sqlalchemy import create_engine, MetaData, Table181182 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)182 engine = create_engine('sqlite:////tmp/test.db')183 metadata = MetaData(bind=engine)184185Then you can either declare the tables in your code like in the examples186above, or automatically load them::
32 unmodified lines
modified:docs/patterns/wtforms.rst+3 added-3 removed
96 unmodified lines
97This macro accepts a couple of keyword arguments that are forwarded to98WTForm's field function, which renders the field for us. The keyword99arguments will be inserted as HTML attributes. So, for example, you can100call ``render_field(form.username, class='username')`` to add a class to101the input element. Note that WTForms returns standard Python unicode102strings, so we have to tell Jinja2 that this data is already HTML-escaped103with the ``|safe`` filter.101the input element. Note that WTForms returns standard Python strings,102so we have to tell Jinja2 that this data is already HTML-escaped with103the ``|safe`` filter.104105Here is the :file:`register.html` template for the function we used above, which106takes advantage of the :file:`_formhelpers.html` template:107
19 unmodified lines
modified:docs/tutorial/tests.rst+2 added-2 removed
299 unmodified lines
300URL when the register view redirects to the login view.301302:attr:`~Response.data` contains the body of the response as bytes. If303you expect a certain value to render on the page, check that it's in304``data``. Bytes must be compared to bytes. If you want to compare305Unicode text, use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`304``data``. Bytes must be compared to bytes. If you want to compare text,305use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`306instead.307308``pytest.mark.parametrize`` tells Pytest to run the same test function309with different arguments. You use it here to test different invalid
252 unmodified lines
modified:docs/config.rst+7 added-7 removed
159 unmodified lines
160.. py:data:: SECRET_KEY161162 A secret key that will be used for securely signing the session cookie163 and can be used for any other security related needs by extensions or your164 application. It should be a long random string of bytes, although unicode165 is accepted too. For example, copy the output of this to your config::164 application. It should be a long random ``bytes`` or ``str``. For165 example, copy the output of this to your config::166167 $ python -c 'import os; print(os.urandom(16))'168 b'_5#y2L"F4Q8z\n\xec]/'169
131 unmodified lines
301 Default: ``None``302303.. py:data:: JSON_AS_ASCII304305 Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON306 will be returned as a Unicode string, or encoded as ``UTF-8`` by307 ``jsonify``. This has security implications when rendering the JSON into308 JavaScript in templates, and should typically remain enabled.305 Serialize objects to ASCII-encoded JSON. If this is disabled, the306 JSON returned from ``jsonify`` will contain Unicode characters. This307 has security implications when rendering the JSON into JavaScript in308 templates, and should typically remain enabled.309310 Default: ``True``311312.. py:data:: JSON_SORT_KEYS
364 unmodified lines
677 /instance678679- Installed module or package::680681 $PREFIX/lib/python2.X/site-packages/myapp681 $PREFIX/lib/pythonX.Y/site-packages/myapp682 $PREFIX/var/myapp-instance683684 ``$PREFIX`` is the prefix of your Python installation. This can be685 ``/usr`` or the path to your virtualenv. You can print the value of
32 unmodified lines
modified:docs/design.rst+8 added-8 removed
107 unmodified lines
108has a certain understanding about how things work. On the surface they109all work the same: you tell the engine to evaluate a template with a set110of variables and take the return value as string.111112But that's about where similarities end. Jinja2 for example has an113extensive filter system, a certain way to do template inheritance, support114for reusable blocks (macros) that can be used from inside templates and115also from Python code, uses Unicode for all operations, supports116iterative template rendering, configurable syntax and more. On the other117hand an engine like Genshi is based on XML stream evaluation, template118inheritance by taking the availability of XPath into account and more.119Mako on the other hand treats templates similar to Python modules.112But that's about where similarities end. Jinja2 for example has an113extensive filter system, a certain way to do template inheritance,114support for reusable blocks (macros) that can be used from inside115templates and also from Python code, supports iterative template116rendering, configurable syntax and more. On the other hand an engine117like Genshi is based on XML stream evaluation, template inheritance by118taking the availability of XPath into account and more. Mako on the119other hand treats templates similar to Python modules.120121When it comes to connecting a template engine with an application or122framework there is more than just rendering templates. For instance,123Flask uses Jinja2's extensive autoescaping support. Also it provides
68 unmodified lines
modified:docs/index.rst-3 removed
82 unmodified lines
8384 design85 htmlfaq86 security87 unicode87 extensiondev89 styleguide90 upgrading88 changelog89 license90 contributing
modified:docs/installation.rst+13 added-72 removed
1 unmodified line
23Installation4============567Python Version8--------------99We recommend using the latest version of Python 3. Flask supports Python 3.510and newer, Python 2.7, and PyPy.10We recommend using the latest version of Python. Flask supports Python113.6 and newer.121314Dependencies15------------1617These distributions will be installed automatically when installing Flask.
14 unmodified lines
32.. _MarkupSafe: https://palletsprojects.com/p/markupsafe/33.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/34.. _Click: https://palletsprojects.com/p/click/353637Optional dependencies38~~~~~~~~~~~~~~~~~~~~~3940These distributions will not be installed automatically. Flask will detect and
12 unmodified lines
53.. _SimpleJSON: https://simplejson.readthedocs.io/54.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme55.. _watchdog: https://pythonhosted.org/watchdog/565758Virtual environments59--------------------6061Use a virtual environment to manage the dependencies for your project, both in
7 unmodified lines
69Virtual environments are independent groups of Python libraries, one for each70project. Packages installed for one project will not affect other projects or71the operating system's packages.7269Python 3 comes bundled with the :mod:`venv` module to create virtual70environments. If you're using a modern version of Python, you can continue on71to the next section.73Python comes bundled with the :mod:`venv` module to create virtual74environments.7573If you're using Python 2, see :ref:`install-install-virtualenv` first.7675.. _install-create-env:7677Create an environment78~~~~~~~~~~~~~~~~~~~~~7980Create a project folder and a :file:`venv` folder within:
9 unmodified lines
90.. code-block:: bat9192 $ py -3 -m venv venv9394If you needed to install virtualenv because you are using Python 2, use95the following command instead:9497.. code-block:: sh9899 $ python2 -m virtualenv venv100101On Windows:102103.. code-block:: bat104105 > \Python27\Scripts\virtualenv.exe venv10695.. _install-activate-env:9697Activate the environment98~~~~~~~~~~~~~~~~~~~~~~~~
9 unmodified lines
108.. code-block:: bat109110 > venv\Scripts\activate111124Your shell prompt will change to show the name of the activated environment.112Your shell prompt will change to show the name of the activated113environment.114115116Install Flask117-------------118129Within the activated environment, use the following command to install Flask:119Within the activated environment, use the following command to install120Flask:121122.. code-block:: sh123124 $ pip install Flask125126Flask is now installed. Check out the :doc:`/quickstart` or go to the127:doc:`Documentation Overview </index>`.137138Living on the edge139~~~~~~~~~~~~~~~~~~140141If you want to work with the latest Flask code before it's released, install or142update the code from the master branch:143144.. code-block:: sh145146 $ pip install -U https://github.com/pallets/flask/archive/master.tar.gz147148.. _install-install-virtualenv:149150Install virtualenv151------------------152153If you are using Python 2, the venv module is not available. Instead,154install `virtualenv`_.155156On Linux, virtualenv is provided by your package manager:157158.. code-block:: sh159160 # Debian, Ubuntu161 $ sudo apt-get install python-virtualenv162163 # CentOS, Fedora164 $ sudo yum install python-virtualenv165166 # Arch167 $ sudo pacman -S python-virtualenv168169If you are on Mac OS X or Windows, download `get-pip.py`_, then:170171.. code-block:: sh172173 $ sudo python2 Downloads/get-pip.py174 $ sudo python2 -m pip install virtualenv175176On Windows, as an administrator:177178.. code-block:: bat179180 > \Python27\python.exe Downloads\get-pip.py181 > \Python27\python.exe -m pip install virtualenv182183Now you can return above and :ref:`install-create-env`.184185.. _virtualenv: https://virtualenv.pypa.io/186.. _get-pip.py: https://bootstrap.pypa.io/get-pip.py
modified:docs/quickstart.rst+1 added-2 removed
291 unmodified lines
2922931. Reversing is often more descriptive than hard-coding the URLs.2942. You can change your URLs in one go instead of needing to remember to295 manually change hard-coded URLs.2963. URL building handles escaping of special characters and Unicode data297 transparently.2963. URL building handles escaping of special characters transparently.2974. The generated paths are always absolute, avoiding unexpected behavior298 of relative paths in browsers.2995. If your application is placed outside the URL root, for example, in300 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly
621 unmodified lines
deleted:docs/styleguide.rst-200 removed
1Pocoo Styleguide2================34The Pocoo styleguide is the styleguide for all Pocoo Projects, including5Flask. This styleguide is a requirement for Patches to Flask and a6recommendation for Flask extensions.78In general the Pocoo Styleguide closely follows :pep:`8` with some small9differences and extensions.1011General Layout12--------------1314Indentation:15 4 real spaces. No tabs, no exceptions.1617Maximum line length:18 79 characters with a soft limit for 84 if absolutely necessary. Try19 to avoid too nested code by cleverly placing `break`, `continue` and20 `return` statements.2122Continuing long statements:23 To continue a statement you can use backslashes in which case you should24 align the next line with the last dot or equal sign, or indent four25 spaces::2627 this_is_a_very_long(function_call, 'with many parameters') \28 .that_returns_an_object_with_an_attribute2930 MyModel.query.filter(MyModel.scalar > 120) \31 .order_by(MyModel.name.desc()) \32 .limit(10)3334 If you break in a statement with parentheses or braces, align to the35 braces::3637 this_is_a_very_long(function_call, 'with many parameters',38 23, 42, 'and even more')3940 For lists or tuples with many items, break immediately after the41 opening brace::4243 items = [44 'this is the first', 'set of items', 'with more items',45 'to come in this line', 'like this'46 ]4748Blank lines:49 Top level functions and classes are separated by two lines, everything50 else by one. Do not use too many blank lines to separate logical51 segments in code. Example::5253 def hello(name):54 print f'Hello {name}!'555657 def goodbye(name):58 print f'See you {name}.'596061 class MyClass(object):62 """This is a simple docstring"""6364 def __init__(self, name):65 self.name = name6667 def get_annoying_name(self):68 return self.name.upper() + '!!!!111'6970Expressions and Statements71--------------------------7273General whitespace rules:74 - No whitespace for unary operators that are not words75 (e.g.: ``-``, ``~`` etc.) as well on the inner side of parentheses.76 - Whitespace is placed between binary operators.7778 Good::7980 exp = -1.0581 value = (item_value / item_count) * offset / exp82 value = my_list[index]83 value = my_dict['key']8485 Bad::8687 exp = - 1.0588 value = ( item_value / item_count ) * offset / exp89 value = (item_value/item_count)*offset/exp90 value=( item_value/item_count ) * offset/exp91 value = my_list[ index ]92 value = my_dict ['key']9394Yoda statements are a no-go:95 Never compare constant with variable, always variable with constant:9697 Good::9899 if method == 'md5':100 pass101102 Bad::103104 if 'md5' == method:105 pass106107Comparisons:108 - against arbitrary types: ``==`` and ``!=``109 - against singletons with ``is`` and ``is not`` (eg: ``foo is not110 None``)111 - never compare something with ``True`` or ``False`` (for example never112 do ``foo == False``, do ``not foo`` instead)113114Negated containment checks:115 use ``foo not in bar`` instead of ``not foo in bar``116117Instance checks:118 ``isinstance(a, C)`` instead of ``type(A) is C``, but try to avoid119 instance checks in general. Check for features.120121122Naming Conventions123------------------124125- Class names: ``CamelCase``, with acronyms kept uppercase (``HTTPWriter``126 and not ``HttpWriter``)127- Variable names: ``lowercase_with_underscores``128- Method and function names: ``lowercase_with_underscores``129- Constants: ``UPPERCASE_WITH_UNDERSCORES``130- precompiled regular expressions: ``name_re``131132Protected members are prefixed with a single underscore. Double133underscores are reserved for mixin classes.134135On classes with keywords, trailing underscores are appended. Clashes with136builtins are allowed and **must not** be resolved by appending an137underline to the variable name. If the function needs to access a138shadowed builtin, rebind the builtin to a different name instead.139140Function and method arguments:141 - class methods: ``cls`` as first parameter142 - instance methods: ``self`` as first parameter143 - lambdas for properties might have the first parameter replaced144 with ``x`` like in ``display_name = property(lambda x: x.real_name145 or x.username)``146147148Docstrings149----------150151Docstring conventions:152 All docstrings are formatted with reStructuredText as understood by153 Sphinx. Depending on the number of lines in the docstring, they are154 laid out differently. If it's just one line, the closing triple155 quote is on the same line as the opening, otherwise the text is on156 the same line as the opening quote and the triple quote that closes157 the string on its own line::158159 def foo():160 """This is a simple docstring"""161162163 def bar():164 """This is a longer docstring with so much information in there165 that it spans three lines. In this case the closing triple quote166 is on its own line.167 """168169Module header:170 The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173174 # -*- coding: utf-8 -*-175 """176 package.module177 ~~~~~~~~~~~~~~178179 A brief description goes here.180181 :copyright: (c) YEAR by AUTHOR.182 :license: LICENSE_NAME, see LICENSE_FILE for more details.183 """184185 Please keep in mind that proper copyrights and license files are a186 requirement for approved Flask extensions.187188189Comments190--------191192Rules for comments are similar to docstrings. Both are formatted with193reStructuredText. If a comment is used to document an attribute, put a194colon after the opening pound sign (``#``)::195196 class User(object):197 #: the name of the user as unicode string198 name = Column(String)199 #: the sha1 hash of the password + inline salt200 pw_hash = Column(String)
deleted:docs/unicode.rst-107 removed
1Unicode in Flask2================34Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to5text. Not only these libraries, also the majority of web related Python6libraries that deal with text. If you don't know Unicode so far, you7should probably read `The Absolute Minimum Every Software Developer8Absolutely, Positively Must Know About Unicode and Character Sets9<https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/>`_.10This part of the documentation just tries to cover the very basics so11that you have a pleasant experience with Unicode related things.1213Automatic Conversion14--------------------1516Flask has a few assumptions about your application (which you can change17of course) that give you basic and painless Unicode support:1819- the encoding for text on your website is UTF-820- internally you will always use Unicode exclusively for text except21 for literal strings with only ASCII character points.22- encoding and decoding happens whenever you are talking over a protocol23 that requires bytes to be transmitted.2425So what does this mean to you?2627HTTP is based on bytes. Not only the protocol, also the system used to28address documents on servers (so called URIs or URLs). However HTML which29is usually transmitted on top of HTTP supports a large variety of30character sets and which ones are used, are transmitted in an HTTP header.31To not make this too complex Flask just assumes that if you are sending32Unicode out you want it to be UTF-8 encoded. Flask will do the encoding33and setting of the appropriate headers for you.3435The same is true if you are talking to databases with the help of36SQLAlchemy or a similar ORM system. Some databases have a protocol that37already transmits Unicode and if they do not, SQLAlchemy or your other ORM38should take care of that.3940The Golden Rule41---------------4243So the rule of thumb: if you are not dealing with binary data, work with44Unicode. What does working with Unicode in Python 2.x mean?4546- as long as you are using ASCII code points only (basically numbers,47 some special characters of Latin letters without umlauts or anything48 fancy) you can use regular string literals (``'Hello World'``).49- if you need anything else than ASCII in a string you have to mark50 this string as Unicode string by prefixing it with a lowercase `u`.51 (like ``u'Hänsel und Gretel'``)52- if you are using non-Unicode characters in your Python files you have53 to tell Python which encoding your file uses. Again, I recommend54 UTF-8 for this purpose. To tell the interpreter your encoding you can55 put the ``# -*- coding: utf-8 -*-`` into the first or second line of56 your Python source file.57- Jinja is configured to decode the template files from UTF-8. So make58 sure to tell your editor to save the file as UTF-8 there as well.5960Encoding and Decoding Yourself61------------------------------6263If you are talking with a filesystem or something that is not really based64on Unicode you will have to ensure that you decode properly when working65with Unicode interface. So for example if you want to load a file on the66filesystem and embed it into a Jinja2 template you will have to decode it67from the encoding of that file. Here the old problem that text files do68not specify their encoding comes into play. So do yourself a favour and69limit yourself to UTF-8 for text files as well.7071Anyways. To load such a file with Unicode you can use the built-in72:meth:`str.decode` method::7374 def read_file(filename, charset='utf-8'):75 with open(filename, 'r') as f:76 return f.read().decode(charset)7778To go from Unicode into a specific charset such as UTF-8 you can use the79:meth:`unicode.encode` method::8081 def write_file(filename, contents, charset='utf-8'):82 with open(filename, 'w') as f:83 f.write(contents.encode(charset))8485Configuring Editors86-------------------8788Most editors save as UTF-8 by default nowadays but in case your editor is89not configured to do this you have to change it. Here some common ways to90set your editor to store as UTF-8:9192- Vim: put ``set enc=utf-8`` to your ``.vimrc`` file.9394- Emacs: either use an encoding cookie or put this into your ``.emacs``95 file::9697 (prefer-coding-system 'utf-8)98 (setq default-buffer-file-coding-system 'utf-8)99100- Notepad++:101102 1. Go to *Settings -> Preferences ...*103 2. Select the "New Document/Default Directory" tab104 3. Select "UTF-8 without BOM" as encoding105106 It is also recommended to use the Unix newline format, you can select107 it in the same panel but this is not a requirement.
deleted:docs/upgrading.rst-472 removed
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.1617Use the :command:`pip` command to upgrade your existing Flask installation by18providing the ``--upgrade`` parameter::1920 $ pip install --upgrade Flask2122.. _upgrading-to-012:2324Version 0.1225------------2627Changes to send_file28````````````````````2930The ``filename`` is no longer automatically inferred from file-like objects.31This means that the following code will no longer automatically have32``X-Sendfile`` support, etag generation or MIME-type guessing::3334 response = send_file(open('/path/to/file.txt'))3536Any of the following is functionally equivalent::3738 fname = '/path/to/file.txt'3940 # Just pass the filepath directly41 response = send_file(fname)4243 # Set the MIME-type and ETag explicitly44 response = send_file(open(fname), mimetype='text/plain')45 response.set_etag(...)4647 # Set `attachment_filename` for MIME-type guessing48 # ETag still needs to be manually set49 response = send_file(open(fname), attachment_filename=fname)50 response.set_etag(...)5152The reason for this is that some file-like objects have an invalid or even53misleading ``name`` attribute. Silently swallowing errors in such cases was not54a satisfying solution.5556Additionally the default of falling back to ``application/octet-stream`` has57been restricted. If Flask can't guess one or the user didn't provide one, the58function fails if no filename information was provided.5960.. _upgrading-to-011:6162Version 0.1163------------64650.11 is an odd release in the Flask release cycle because it was supposed66to be the 1.0 release. However because there was such a long lead time up67to the release we decided to push out a 0.11 release first with some68changes removed to make the transition easier. If you have been tracking69the master branch which was 1.0 you might see some unexpected changes.7071In case you did track the master branch you will notice that72:command:`flask --app` is removed now.73You need to use the environment variable to specify an application.7475Debugging76`````````7778Flask 0.11 removed the ``debug_log_format`` attribute from Flask79applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can80be used to disable the default log handlers and custom log handlers can be81set up.8283Error handling84``````````````8586The behavior of error handlers was changed.87The precedence of handlers used to be based on the decoration/call order of88:meth:`~flask.Flask.errorhandler` and89:meth:`~flask.Flask.register_error_handler`, respectively.90Now the inheritance hierarchy takes precedence and handlers for more91specific exception classes are executed instead of more general ones.92See :ref:`error-handlers` for specifics.9394Trying to register a handler on an instance now raises :exc:`ValueError`.9596.. note::9798 There used to be a logic error allowing you to register handlers99 only for exception *instances*. This was unintended and plain wrong,100 and therefore was replaced with the intended behavior of registering101 handlers only using exception classes and HTTP error codes.102103Templating104``````````105106The :func:`~flask.templating.render_template_string` function has changed to107autoescape template variables by default. This better matches the behavior108of :func:`~flask.templating.render_template`.109110Extension imports111`````````````````112113Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114``flask_foo``.115116The old form still works, but Flask will issue a117``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118way. We also provide a migration utility called `flask-ext-migrate119<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to120automatically rewrite your imports for this.121122.. _upgrading-to-010:123124Version 0.10125------------126127The biggest change going from 0.9 to 0.10 is that the cookie serialization128format changed from pickle to a specialized JSON format. This change has129been done in order to avoid the damage an attacker can do if the secret130key is leaked. When you upgrade you will notice two major changes: all131sessions that were issued before the upgrade are invalidated and you can132only store a limited amount of types in the session. The new sessions are133by design much more restricted to only allow JSON with a few small134extensions for tuples and strings with HTML markup.135136In order to not break people's sessions it is possible to continue using137the old session system by using the `Flask-OldSessions`_ extension.138139Flask also started storing the :data:`flask.g` object on the application140context instead of the request context. This change should be transparent141for you but it means that you now can store things on the ``g`` object142when there is no request context yet but an application context. The old143``flask.Flask.request_globals_class`` attribute was renamed to144:attr:`flask.Flask.app_ctx_globals_class`.145146.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147148Version 0.9149-----------150151The behavior of returning tuples from a function was simplified. If you152return a tuple it no longer defines the arguments for the response object153you're creating, it's now always a tuple in the form ``(response, status,154headers)`` where at least one item has to be provided. If you depend on155the old behavior, you can add it easily by subclassing Flask::156157 class TraditionalFlask(Flask):158 def make_response(self, rv):159 if isinstance(rv, tuple):160 return self.response_class(*rv)161 return Flask.make_response(self, rv)162163If you maintain an extension that was using :data:`~flask._request_ctx_stack`164before, please consider changing to :data:`~flask._app_ctx_stack` if it makes165sense for your extension. For instance, the app context stack makes sense for166extensions which connect to databases. Using the app context stack instead of167the request context stack will make extensions more readily handle use cases168outside of requests.169170Version 0.8171-----------172173Flask introduced a new session interface system. We also noticed that174there was a naming collision between ``flask.session`` the module that175implements sessions and :data:`flask.session` which is the global session176object. With that introduction we moved the implementation details for177the session system into a new module called :mod:`flask.sessions`. If you178used the previously undocumented session support we urge you to upgrade.179180If invalid JSON data was submitted Flask will now raise a181:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the182default :exc:`ValueError` bubble up. This has the advantage that you no183longer have to handle that error to avoid an internal server error showing184up for the user. If you were catching this down explicitly in the past185as :exc:`ValueError` you will need to change this.186187Due to a bug in the test client Flask 0.7 did not trigger teardown188handlers when the test client was used in a with statement. This was189since fixed but might require some changes in your test suites if you190relied on this behavior.191192Version 0.7193-----------194195In Flask 0.7 we cleaned up the code base internally a lot and did some196backwards incompatible changes that make it easier to implement larger197applications with Flask. Because we want to make upgrading as easy as198possible we tried to counter the problems arising from these changes by199providing a script that can ease the transition.200201The script scans your whole application and generates a unified diff with202changes it assumes are safe to apply. However as this is an automated203tool it won't be able to find all use cases and it might miss some. We204internally spread a lot of deprecation warnings all over the place to make205it easy to find pieces of code that it was unable to upgrade.206207We strongly recommend that you hand review the generated patchfile and208only apply the chunks that look good.209210If you are using git as version control system for your project we211recommend applying the patch with ``path -p1 < patchfile.diff`` and then212using the interactive commit feature to only apply the chunks that look213good.214215To apply the upgrade script do the following:2162171. Download the script: `flask-07-upgrade.py218 <https://raw.githubusercontent.com/pallets/flask/0.12.3/scripts/flask-07-upgrade.py>`_2192. Run it in the directory of your application::220221 $ python flask-07-upgrade.py > patchfile.diff2222233. Review the generated patchfile.2244. Apply the patch::225226 $ patch -p1 < patchfile.diff2272285. If you were using per-module template folders you need to move some229 templates around. Previously if you had a folder named :file:`templates`230 next to a blueprint named ``admin`` the implicit template path231 automatically was :file:`admin/index.html` for a template file called232 :file:`templates/index.html`. This no longer is the case. Now you need233 to name the template :file:`templates/admin/index.html`. The tool will234 not detect this so you will have to do that on your own.235236Please note that deprecation warnings are disabled by default starting237with Python 2.7. In order to see the deprecation warnings that might be238emitted you have to enabled them with the :mod:`warnings` module.239240If you are working with windows and you lack the ``patch`` command line241utility you can get it as part of various Unix runtime environments for242windows including cygwin, msysgit or ming32. Also source control systems243like svn, hg or git have builtin support for applying unified diffs as244generated by the tool. Check the manual of your version control system245for more information.246247Bug in Request Locals248`````````````````````249250Due to a bug in earlier implementations the request local proxies now251raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they252are unbound. If you caught these exceptions with :exc:`AttributeError`253before, you should catch them with :exc:`RuntimeError` now.254255Additionally the :func:`~flask.send_file` function is now issuing256deprecation warnings if you depend on functionality that will be removed257in Flask 0.11. Previously it was possible to use etags and mimetypes258when file objects were passed. This was unreliable and caused issues259for a few setups. If you get a deprecation warning, make sure to260update your application to work with either filenames there or disable261etag attaching and attach them yourself.262263Old code::264265 return send_file(my_file_object)266 return send_file(my_file_object)267268New code::269270 return send_file(my_file_object, add_etags=False)271272.. _upgrading-to-new-teardown-handling:273274Upgrading to new Teardown Handling275``````````````````````````````````276277We streamlined the behavior of the callbacks for request handling. For278things that modify the response the :meth:`~flask.Flask.after_request`279decorators continue to work as expected, but for things that absolutely280must happen at the end of request we introduced the new281:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that282change also made after-request work differently under error conditions.283It's not consistently skipped if exceptions happen whereas previously it284might have been called twice to ensure it is executed at the end of the285request.286287If you have database connection code that looks like this::288289 @app.after_request290 def after_request(response):291 g.db.close()292 return response293294You are now encouraged to use this instead::295296 @app.teardown_request297 def after_request(exception):298 if hasattr(g, 'db'):299 g.db.close()300301On the upside this change greatly improves the internal code flow and302makes it easier to customize the dispatching and error handling. This303makes it now a lot easier to write unit tests as you can prevent closing304down of database connections for a while. You can take advantage of the305fact that the teardown callbacks are called when the response context is306removed from the stack so a test can query the database after request307handling::308309 with app.test_client() as client:310 resp = client.get('/')311 # g.db is still bound if there is such a thing312313 # and here it's gone314315Manual Error Handler Attaching316``````````````````````````````317318While it is still possible to attach error handlers to319:attr:`Flask.error_handlers` it's discouraged to do so and in fact320deprecated. In general we no longer recommend custom error handler321attaching via assignments to the underlying dictionary due to the more322complex internal handling to support arbitrary exception classes and323blueprints. See :meth:`Flask.errorhandler` for more information.324325The proper upgrade is to change this::326327 app.error_handlers[403] = handle_error328329Into this::330331 app.register_error_handler(403, handle_error)332333Alternatively you should just attach the function with a decorator::334335 @app.errorhandler(403)336 def handle_error(e):337 ...338339(Note that :meth:`register_error_handler` is new in Flask 0.7)340341Blueprint Support342`````````````````343344Blueprints replace the previous concept of “Modules” in Flask. They345provide better semantics for various features and work better with large346applications. The update script provided should be able to upgrade your347applications automatically, but there might be some cases where it fails348to upgrade. What changed?349350- Blueprints need explicit names. Modules had an automatic name351 guessing scheme where the shortname for the module was taken from the352 last part of the import module. The upgrade script tries to guess353 that name but it might fail as this information could change at354 runtime.355- Blueprints have an inverse behavior for :meth:`url_for`. Previously356 ``.foo`` told :meth:`url_for` that it should look for the endpoint357 ``foo`` on the application. Now it means “relative to current module”.358 The script will inverse all calls to :meth:`url_for` automatically for359 you. It will do this in a very eager way so you might end up with360 some unnecessary leading dots in your code if you're not using361 modules.362- Blueprints do not automatically provide static folders. They will363 also no longer automatically export templates from a folder called364 :file:`templates` next to their location however but it can be enabled from365 the constructor. Same with static files: if you want to continue366 serving static files you need to tell the constructor explicitly the367 path to the static folder (which can be relative to the blueprint's368 module path).369- Rendering templates was simplified. Now the blueprints can provide370 template folders which are added to a general template searchpath.371 This means that you need to add another subfolder with the blueprint's372 name into that folder if you want :file:`blueprintname/template.html` as373 the template name.374375If you continue to use the ``Module`` object which is deprecated, Flask will376restore the previous behavior as good as possible. However we strongly377recommend upgrading to the new blueprints as they provide a lot of useful378improvement such as the ability to attach a blueprint multiple times,379blueprint specific error handlers and a lot more.380381382Version 0.6383-----------384385Flask 0.6 comes with a backwards incompatible change which affects the386order of after-request handlers. Previously they were called in the order387of the registration, now they are called in reverse order. This change388was made so that Flask behaves more like people expected it to work and389how other systems handle request pre- and post-processing. If you390depend on the order of execution of post-request functions, be sure to391change the order.392393Another change that breaks backwards compatibility is that context394processors will no longer override values passed directly to the template395rendering function. If for example ``request`` is as variable passed396directly to the template, the default context processor will not override397it with the current request object. This makes it easier to extend398context processors later to inject additional variables without breaking399existing template not expecting them.400401Version 0.5402-----------403404Flask 0.5 is the first release that comes as a Python package instead of a405single module. There were a couple of internal refactoring so if you406depend on undocumented internal details you probably have to adapt the407imports.408409The following changes may be relevant to your application:410411- autoescaping no longer happens for all templates. Instead it is412 configured to only happen on files ending with ``.html``, ``.htm``,413 ``.xml`` and ``.xhtml``. If you have templates with different414 extensions you should override the415 :meth:`~flask.Flask.select_jinja_autoescape` method.416- Flask no longer supports zipped applications in this release. This417 functionality might come back in future releases if there is demand418 for this feature. Removing support for this makes the Flask internal419 code easier to understand and fixes a couple of small issues that make420 debugging harder than necessary.421- The ``create_jinja_loader`` function is gone. If you want to customize422 the Jinja loader now, use the423 :meth:`~flask.Flask.create_jinja_environment` method instead.424425Version 0.4426-----------427428For application developers there are no changes that require changes in429your code. In case you are developing on a Flask extension however, and430that extension has a unittest-mode you might want to link the activation431of that mode to the new ``TESTING`` flag.432433Version 0.3434-----------435436Flask 0.3 introduces configuration support and logging as well as437categories for flashing messages. All these are features that are 100%438backwards compatible but you might want to take advantage of them.439440Configuration Support441`````````````````````442443The configuration support makes it easier to write any kind of application444that requires some sort of configuration. (Which most likely is the case445for any application out there).446447If you previously had code like this::448449 app.debug = DEBUG450 app.secret_key = SECRET_KEY451452You no longer have to do that, instead you can just load a configuration453into the config object. How this works is outlined in :ref:`config`.454455Logging Integration456```````````````````457458Flask now configures a logger for you with some basic and useful defaults.459If you run your application in production and want to profit from460automatic error logging, you might be interested in attaching a proper log461handler. Also you can start logging warnings and errors into the logger462when appropriately. For more information on that, read463:ref:`application-errors`.464465Categories for Flash Messages466`````````````````````````````467468Flash messages can now have categories attached. This makes it possible469to render errors, warnings or regular messages differently for example.470This is an opt-in feature because it requires some rethinking in the code.471472Read all about that in the :ref:`message-flashing-pattern` pattern.
modified:src/flask/app.py+5 added-7 removed
189 unmodified lines
190 :param instance_relative_config: if set to ``True`` relative filenames191 for loading the config are assumed to192 be relative to the instance path instead193 of the application root.194 :param root_path: Flask by default will automatically calculate the path195 to the root of the application. In certain situations196 this cannot be achieved (for instance if the package197 is a Python 3 namespace package) and needs to be198 manually defined.194 :param root_path: The path to the root of the application files.195 This should only be set manually when it can't be detected196 automatically, such as for namespace packages.197 """198199 #: The class that is used for request objects. See :class:`~flask.Request`200 #: for more information.
1822 unmodified lines
2023 must return a response. Returning ``None``, or the view ending2024 without returning, is not allowed. The following types are allowed2025 for ``view_rv``:20262029 ``str`` (``unicode`` in Python 2)2027 ``str``2028 A response object is created with the string encoded to UTF-82029 as the body.20302033 ``bytes`` (``str`` in Python 2)2031 ``bytes``2032 A response object is created with the bytes as the body.20332034 ``dict``2035 A dictionary that will be jsonify'd before being returned.
421 unmodified lines
modified:src/flask/helpers.py+2 added-2 removed
907 unmodified lines
908 filename = sys.modules[root_mod_name].__file__909 package_path = os.path.abspath(os.path.dirname(filename))910911 # In case the root module is a package we need to chop of the912 # rightmost part. This needs to go through a helper function913 # because of python 3.3 namespace packages.912 # rightmost part. This needs to go through a helper function913 # because of namespace packages.914 if _matching_loader_thinks_module_is_package(loader, root_mod_name):915 package_path = os.path.dirname(package_path)916917 return package_path
250 unmodified lines
modified:CHANGES.rst+6 added-9 removed
450 unmodified lines
451Released 2016-05-29, codename Absinthe452453- Added support to serializing top-level arrays to454 :func:`flask.jsonify`. This introduces a security risk in ancient455 browsers. See :ref:`json-security` for details.455 browsers.456- Added before_render_template signal.457- Added ``**kwargs`` to :meth:`flask.Test.test_client` to support458 passing additional keyword arguments to the constructor of459 :attr:`flask.Flask.test_client_class`.
106 unmodified lines
566567Released 2013-06-13, codename Limoncello568569- Changed default cookie serialization format from pickle to JSON to570 limit the impact an attacker can do if the secret key leaks. See571 :ref:`upgrading-to-010` for more information.570 limit the impact an attacker can do if the secret key leaks.571- Added ``template_test`` methods in addition to the already existing572 ``template_filter`` method family.573- Added ``template_global`` methods in addition to the already574 existing ``template_filter`` method family.
20 unmodified lines
595 imported templates by default.596- Added an option to generate non-ascii encoded JSON which should597 result in less bytes being transmitted over the network. It's598 disabled by default to not cause confusion with existing libraries600 that might expect ``flask.json.dumps`` to return bytestrings by601 default.599 that might expect ``flask.json.dumps`` to return bytes by default.600- ``flask.g`` is now stored on the app context instead of the request601 context.602- ``flask.g`` now gained a ``get()`` method for not erroring out on603 non existing items.
155 unmodified lines
759 modules are located but also an instance path which is the760 designated place to drop files that are modified at runtime (uploads761 etc.). Also this is conceptually only instance depending and outside762 version control so it's the perfect place to put configuration files765 etc. For more information see :ref:`instance-folders`.763 etc.764- Added the ``APPLICATION_ROOT`` configuration variable.765- Implemented :meth:`~flask.testing.TestClient.session_transaction` to766 easily modify sessions from the test environment.767- Refactored test client internally. The ``APPLICATION_ROOT``
71 unmodified lines
839- Implemented a silent flag for ``config.from_pyfile``.840- Added ``teardown_request`` decorator, for functions that should run841 at the end of a request regardless of whether an exception occurred.842 Also the behavior for ``after_request`` was changed. It's now no845 longer executed when an exception is raised. See846 :ref:`upgrading-to-new-teardown-handling`843 longer executed when an exception is raised.844- Implemented :func:`flask.has_request_context`845- Deprecated ``init_jinja_globals``. Override the846 :meth:`~flask.Flask.create_jinja_environment` method instead to847 achieve the same functionality.
8 unmodified lines
856 can provide custom error messages from a central hub for certain857 errors that might occur during request processing (for instance858 database connection errors, timeouts from remote resources etc.).859- Blueprints can provide blueprint specific error handlers.863- Implemented generic :ref:`views` (class-based views).860- Implemented generic class-based views.861862863Version 0.6.1864-------------
171 unmodified lines
modified:CONTRIBUTING.rst+3 added-2 removed
133 unmodified lines
134depends on which part of Flask you're working on. Travis-CI will run the full135suite when you submit your pull request.136137The full test suite takes a long time to run because it tests multiple138combinations of Python and dependencies. You need to have Python 2.7, 3.4,1393.5, 3.6, 3.7 and PyPy 2.7 installed to run all of the environments. Then run::138combinations of Python and dependencies. If you don't have a Python139version installed, it will be skipped with a warning message at the end.140Run::141142 tox143144Running test coverage
53 unmodified lines