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
Provenance
- Commit
7673835- Tree
0b9d7d4- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
96b4dca
17 files changed+53 added−908 removed
modified:docs/deploying/mod_wsgi.rst-5 removed
209 unmodified lines210 211 Add the following lines to the top of your ``.wsgi`` file::212 213 activate_this = '/path/to/env/bin/activate_this.py'214- execfile(activate_this, dict(__file__=activate_this))215-216-For Python 3 add the following lines to the top of your ``.wsgi`` file::217-218- activate_this = '/path/to/env/bin/activate_this.py'214 with open(activate_this) as file_:215 exec(file_.read(), dict(__file__=activate_this))216 217 This sets up the load paths according to the settings of the virtual1 unmodified linemodified:docs/patterns/distribute.rst-4 removed
17 unmodified lines18 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.21 22-If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org,23-you will already have pip and setuptools on your system. Otherwise, you24-will need to install them yourself.25-22 Flask itself, and all the libraries you can find on PyPI are distributed with23 either setuptools or distutils.24 25 In this case we assume your application is called148 unmodified linesmodified:docs/patterns/sqlalchemy.rst+3 added-3 removed
37 unmodified lines38 from sqlalchemy import create_engine39 from sqlalchemy.orm import scoped_session, sessionmaker40 from sqlalchemy.ext.declarative import declarative_base41 42- 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 lines126 127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129 130- 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 lines178 you basically only need the engine::179 180 from sqlalchemy import create_engine, MetaData, Table181 182- engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)182+ engine = create_engine('sqlite:////tmp/test.db')183 metadata = MetaData(bind=engine)184 185 Then you can either declare the tables in your code like in the examples186 above, or automatically load them::32 unmodified linesmodified:docs/patterns/wtforms.rst+3 added-3 removed
96 unmodified lines97 This macro accepts a couple of keyword arguments that are forwarded to98 WTForm's field function, which renders the field for us. The keyword99 arguments will be inserted as HTML attributes. So, for example, you can100 call ``render_field(form.username, class='username')`` to add a class to101-the input element. Note that WTForms returns standard Python unicode102-strings, so we have to tell Jinja2 that this data is already HTML-escaped103-with the ``|safe`` filter.101+the input element. Note that WTForms returns standard Python strings,102+so we have to tell Jinja2 that this data is already HTML-escaped with103+the ``|safe`` filter.104 105 Here is the :file:`register.html` template for the function we used above, which106 takes advantage of the :file:`_formhelpers.html` template:107 19 unmodified linesmodified:docs/tutorial/tests.rst+2 added-2 removed
299 unmodified lines300 URL when the register view redirects to the login view.301 302 :attr:`~Response.data` contains the body of the response as bytes. If303 you 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 compare305-Unicode 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,305+use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`306 instead.307 308 ``pytest.mark.parametrize`` tells Pytest to run the same test function309 with different arguments. You use it here to test different invalid252 unmodified linesmodified:docs/config.rst+7 added-7 removed
159 unmodified lines160 .. py:data:: SECRET_KEY161 162 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::166 167 $ python -c 'import os; print(os.urandom(16))'168 b'_5#y2L"F4Q8z\n\xec]/'169 131 unmodified lines301 Default: ``None``302 303 .. py:data:: JSON_AS_ASCII304 305- 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.309 310 Default: ``True``311 312 .. py:data:: JSON_SORT_KEYS364 unmodified lines677 /instance678 679 - Installed module or package::680 681- $PREFIX/lib/python2.X/site-packages/myapp681+ $PREFIX/lib/pythonX.Y/site-packages/myapp682 $PREFIX/var/myapp-instance683 684 ``$PREFIX`` is the prefix of your Python installation. This can be685 ``/usr`` or the path to your virtualenv. You can print the value of32 unmodified linesmodified:docs/design.rst+8 added-8 removed
107 unmodified lines108 has a certain understanding about how things work. On the surface they109 all work the same: you tell the engine to evaluate a template with a set110 of variables and take the return value as string.111 112-But that's about where similarities end. Jinja2 for example has an113-extensive filter system, a certain way to do template inheritance, support114-for reusable blocks (macros) that can be used from inside templates and115-also from Python code, uses Unicode for all operations, supports116-iterative template rendering, configurable syntax and more. On the other117-hand an engine like Genshi is based on XML stream evaluation, template118-inheritance by taking the availability of XPath into account and more.119-Mako on the other hand treats templates similar to Python modules.112+But that's about where similarities end. Jinja2 for example has an113+extensive filter system, a certain way to do template inheritance,114+support for reusable blocks (macros) that can be used from inside115+templates and also from Python code, supports iterative template116+rendering, configurable syntax and more. On the other hand an engine117+like Genshi is based on XML stream evaluation, template inheritance by118+taking the availability of XPath into account and more. Mako on the119+other hand treats templates similar to Python modules.120 121 When it comes to connecting a template engine with an application or122 framework there is more than just rendering templates. For instance,123 Flask uses Jinja2's extensive autoescaping support. Also it provides68 unmodified linesmodified:docs/index.rst-3 removed
82 unmodified lines83 84 design85 htmlfaq86 security87- unicode87 extensiondev89- styleguide90- upgrading88 changelog89 license90 contributingmodified:docs/installation.rst+13 added-72 removed
1 unmodified line2 3 Installation4 ============5 6+7 Python Version8 --------------9 9-We recommend using the latest version of Python 3. Flask supports Python 3.510-and newer, Python 2.7, and PyPy.10+We recommend using the latest version of Python. Flask supports Python11+3.6 and newer.12 13+14 Dependencies15 ------------16 17 These distributions will be installed automatically when installing Flask.14 unmodified lines32 .. _MarkupSafe: https://palletsprojects.com/p/markupsafe/33 .. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/34 .. _Click: https://palletsprojects.com/p/click/35 36+37 Optional dependencies38 ~~~~~~~~~~~~~~~~~~~~~39 40 These distributions will not be installed automatically. Flask will detect and12 unmodified lines53 .. _SimpleJSON: https://simplejson.readthedocs.io/54 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme55 .. _watchdog: https://pythonhosted.org/watchdog/56 57+58 Virtual environments59 --------------------60 61 Use a virtual environment to manage the dependencies for your project, both in7 unmodified lines69 Virtual environments are independent groups of Python libraries, one for each70 project. Packages installed for one project will not affect other projects or71 the operating system's packages.72 69-Python 3 comes bundled with the :mod:`venv` module to create virtual70-environments. If you're using a modern version of Python, you can continue on71-to the next section.73+Python comes bundled with the :mod:`venv` module to create virtual74+environments.75 73-If you're using Python 2, see :ref:`install-install-virtualenv` first.76 75-.. _install-create-env:76-77 Create an environment78 ~~~~~~~~~~~~~~~~~~~~~79 80 Create a project folder and a :file:`venv` folder within:9 unmodified lines90 .. code-block:: bat91 92 $ py -3 -m venv venv93 94-If you needed to install virtualenv because you are using Python 2, use95-the following command instead:94 97-.. code-block:: sh98-99- $ python2 -m virtualenv venv100-101-On Windows:102-103-.. code-block:: bat104-105- > \Python27\Scripts\virtualenv.exe venv106-95 .. _install-activate-env:96 97 Activate the environment98 ~~~~~~~~~~~~~~~~~~~~~~~~9 unmodified lines108 .. code-block:: bat109 110 > venv\Scripts\activate111 124-Your shell prompt will change to show the name of the activated environment.112+Your shell prompt will change to show the name of the activated113+environment.114 115+116 Install Flask117 -------------118 129-Within the activated environment, use the following command to install Flask:119+Within the activated environment, use the following command to install120+Flask:121 122 .. code-block:: sh123 124 $ pip install Flask125 126 Flask is now installed. Check out the :doc:`/quickstart` or go to the127 :doc:`Documentation Overview </index>`.137-138-Living on the edge139-~~~~~~~~~~~~~~~~~~140-141-If you want to work with the latest Flask code before it's released, install or142-update the code from the master branch:143-144-.. code-block:: sh145-146- $ pip install -U https://github.com/pallets/flask/archive/master.tar.gz147-148-.. _install-install-virtualenv:149-150-Install virtualenv151-------------------152-153-If you are using Python 2, the venv module is not available. Instead,154-install `virtualenv`_.155-156-On Linux, virtualenv is provided by your package manager:157-158-.. code-block:: sh159-160- # Debian, Ubuntu161- $ sudo apt-get install python-virtualenv162-163- # CentOS, Fedora164- $ sudo yum install python-virtualenv165-166- # Arch167- $ sudo pacman -S python-virtualenv168-169-If you are on Mac OS X or Windows, download `get-pip.py`_, then:170-171-.. code-block:: sh172-173- $ sudo python2 Downloads/get-pip.py174- $ sudo python2 -m pip install virtualenv175-176-On Windows, as an administrator:177-178-.. code-block:: bat179-180- > \Python27\python.exe Downloads\get-pip.py181- > \Python27\python.exe -m pip install virtualenv182-183-Now you can return above and :ref:`install-create-env`.184-185-.. _virtualenv: https://virtualenv.pypa.io/186-.. _get-pip.py: https://bootstrap.pypa.io/get-pip.pymodified:docs/quickstart.rst+1 added-2 removed
291 unmodified lines292 293 1. Reversing is often more descriptive than hard-coding the URLs.294 2. You can change your URLs in one go instead of needing to remember to295 manually change hard-coded URLs.296-3. URL building handles escaping of special characters and Unicode data297- transparently.296+3. URL building handles escaping of special characters transparently.297 4. The generated paths are always absolute, avoiding unexpected behavior298 of relative paths in browsers.299 5. If your application is placed outside the URL root, for example, in300 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly621 unmodified linesdeleted:docs/styleguide.rst-200 removed
1-Pocoo Styleguide2-================3-4-The Pocoo styleguide is the styleguide for all Pocoo Projects, including5-Flask. This styleguide is a requirement for Patches to Flask and a6-recommendation for Flask extensions.7-8-In general the Pocoo Styleguide closely follows :pep:`8` with some small9-differences and extensions.10-11-General Layout12---------------13-14-Indentation:15- 4 real spaces. No tabs, no exceptions.16-17-Maximum 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.21-22-Continuing 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::26-27- this_is_a_very_long(function_call, 'with many parameters') \28- .that_returns_an_object_with_an_attribute29-30- MyModel.query.filter(MyModel.scalar > 120) \31- .order_by(MyModel.name.desc()) \32- .limit(10)33-34- If you break in a statement with parentheses or braces, align to the35- braces::36-37- this_is_a_very_long(function_call, 'with many parameters',38- 23, 42, 'and even more')39-40- For lists or tuples with many items, break immediately after the41- opening brace::42-43- items = [44- 'this is the first', 'set of items', 'with more items',45- 'to come in this line', 'like this'46- ]47-48-Blank 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::52-53- def hello(name):54- print f'Hello {name}!'55-56-57- def goodbye(name):58- print f'See you {name}.'59-60-61- class MyClass(object):62- """This is a simple docstring"""63-64- def __init__(self, name):65- self.name = name66-67- def get_annoying_name(self):68- return self.name.upper() + '!!!!111'69-70-Expressions and Statements71---------------------------72-73-General 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.77-78- Good::79-80- exp = -1.0581- value = (item_value / item_count) * offset / exp82- value = my_list[index]83- value = my_dict['key']84-85- Bad::86-87- 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']93-94-Yoda statements are a no-go:95- Never compare constant with variable, always variable with constant:96-97- Good::98-99- if method == 'md5':100- pass101-102- Bad::103-104- if 'md5' == method:105- pass106-107-Comparisons: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)113-114-Negated containment checks:115- use ``foo not in bar`` instead of ``not foo in bar``116-117-Instance checks:118- ``isinstance(a, C)`` instead of ``type(A) is C``, but try to avoid119- instance checks in general. Check for features.120-121-122-Naming Conventions123-------------------124-125-- 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``131-132-Protected members are prefixed with a single underscore. Double133-underscores are reserved for mixin classes.134-135-On classes with keywords, trailing underscores are appended. Clashes with136-builtins are allowed and **must not** be resolved by appending an137-underline to the variable name. If the function needs to access a138-shadowed builtin, rebind the builtin to a different name instead.139-140-Function 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)``146-147-148-Docstrings149-----------150-151-Docstring 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::158-159- def foo():160- """This is a simple docstring"""161-162-163- 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- """168-169-Module 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::173-174- # -*- coding: utf-8 -*-175- """176- package.module177- ~~~~~~~~~~~~~~178-179- A brief description goes here.180-181- :copyright: (c) YEAR by AUTHOR.182- :license: LICENSE_NAME, see LICENSE_FILE for more details.183- """184-185- Please keep in mind that proper copyrights and license files are a186- requirement for approved Flask extensions.187-188-189-Comments190---------191-192-Rules for comments are similar to docstrings. Both are formatted with193-reStructuredText. If a comment is used to document an attribute, put a194-colon after the opening pound sign (``#``)::195-196- 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
1-Unicode in Flask2-================3-4-Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to5-text. Not only these libraries, also the majority of web related Python6-libraries that deal with text. If you don't know Unicode so far, you7-should probably read `The Absolute Minimum Every Software Developer8-Absolutely, 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/>`_.10-This part of the documentation just tries to cover the very basics so11-that you have a pleasant experience with Unicode related things.12-13-Automatic Conversion14---------------------15-16-Flask has a few assumptions about your application (which you can change17-of course) that give you basic and painless Unicode support:18-19-- 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.24-25-So what does this mean to you?26-27-HTTP is based on bytes. Not only the protocol, also the system used to28-address documents on servers (so called URIs or URLs). However HTML which29-is usually transmitted on top of HTTP supports a large variety of30-character sets and which ones are used, are transmitted in an HTTP header.31-To not make this too complex Flask just assumes that if you are sending32-Unicode out you want it to be UTF-8 encoded. Flask will do the encoding33-and setting of the appropriate headers for you.34-35-The same is true if you are talking to databases with the help of36-SQLAlchemy or a similar ORM system. Some databases have a protocol that37-already transmits Unicode and if they do not, SQLAlchemy or your other ORM38-should take care of that.39-40-The Golden Rule41----------------42-43-So the rule of thumb: if you are not dealing with binary data, work with44-Unicode. What does working with Unicode in Python 2.x mean?45-46-- 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.59-60-Encoding and Decoding Yourself61-------------------------------62-63-If you are talking with a filesystem or something that is not really based64-on Unicode you will have to ensure that you decode properly when working65-with Unicode interface. So for example if you want to load a file on the66-filesystem and embed it into a Jinja2 template you will have to decode it67-from the encoding of that file. Here the old problem that text files do68-not specify their encoding comes into play. So do yourself a favour and69-limit yourself to UTF-8 for text files as well.70-71-Anyways. To load such a file with Unicode you can use the built-in72-:meth:`str.decode` method::73-74- def read_file(filename, charset='utf-8'):75- with open(filename, 'r') as f:76- return f.read().decode(charset)77-78-To go from Unicode into a specific charset such as UTF-8 you can use the79-:meth:`unicode.encode` method::80-81- def write_file(filename, contents, charset='utf-8'):82- with open(filename, 'w') as f:83- f.write(contents.encode(charset))84-85-Configuring Editors86--------------------87-88-Most editors save as UTF-8 by default nowadays but in case your editor is89-not configured to do this you have to change it. Here some common ways to90-set your editor to store as UTF-8:91-92-- Vim: put ``set enc=utf-8`` to your ``.vimrc`` file.93-94-- Emacs: either use an encoding cookie or put this into your ``.emacs``95- file::96-97- (prefer-coding-system 'utf-8)98- (setq default-buffer-file-coding-system 'utf-8)99-100-- Notepad++:101-102- 1. Go to *Settings -> Preferences ...*103- 2. Select the "New Document/Default Directory" tab104- 3. Select "UTF-8 without BOM" as encoding105-106- 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
1-Upgrading to Newer Releases2-===========================3-4-Flask itself is changing like any software is changing over time. Most of5-the changes are the nice kind, the kind where you don't have to change6-anything in your code to profit from a new release.7-8-However every once in a while there are changes that do require some9-changes in your code or there are changes that make it possible for you to10-improve your own code quality by taking advantage of new features in11-Flask.12-13-This section of the documentation enumerates all the changes in Flask from14-release to release and how you can change your code to have a painless15-updating experience.16-17-Use the :command:`pip` command to upgrade your existing Flask installation by18-providing the ``--upgrade`` parameter::19-20- $ pip install --upgrade Flask21-22-.. _upgrading-to-012:23-24-Version 0.1225-------------26-27-Changes to send_file28-````````````````````29-30-The ``filename`` is no longer automatically inferred from file-like objects.31-This means that the following code will no longer automatically have32-``X-Sendfile`` support, etag generation or MIME-type guessing::33-34- response = send_file(open('/path/to/file.txt'))35-36-Any of the following is functionally equivalent::37-38- fname = '/path/to/file.txt'39-40- # Just pass the filepath directly41- response = send_file(fname)42-43- # Set the MIME-type and ETag explicitly44- response = send_file(open(fname), mimetype='text/plain')45- response.set_etag(...)46-47- # 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(...)51-52-The reason for this is that some file-like objects have an invalid or even53-misleading ``name`` attribute. Silently swallowing errors in such cases was not54-a satisfying solution.55-56-Additionally the default of falling back to ``application/octet-stream`` has57-been restricted. If Flask can't guess one or the user didn't provide one, the58-function fails if no filename information was provided.59-60-.. _upgrading-to-011:61-62-Version 0.1163-------------64-65-0.11 is an odd release in the Flask release cycle because it was supposed66-to be the 1.0 release. However because there was such a long lead time up67-to the release we decided to push out a 0.11 release first with some68-changes removed to make the transition easier. If you have been tracking69-the master branch which was 1.0 you might see some unexpected changes.70-71-In case you did track the master branch you will notice that72-:command:`flask --app` is removed now.73-You need to use the environment variable to specify an application.74-75-Debugging76-`````````77-78-Flask 0.11 removed the ``debug_log_format`` attribute from Flask79-applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can80-be used to disable the default log handlers and custom log handlers can be81-set up.82-83-Error handling84-``````````````85-86-The behavior of error handlers was changed.87-The 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.90-Now the inheritance hierarchy takes precedence and handlers for more91-specific exception classes are executed instead of more general ones.92-See :ref:`error-handlers` for specifics.93-94-Trying to register a handler on an instance now raises :exc:`ValueError`.95-96-.. note::97-98- 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.102-103-Templating104-``````````105-106-The :func:`~flask.templating.render_template_string` function has changed to107-autoescape template variables by default. This better matches the behavior108-of :func:`~flask.templating.render_template`.109-110-Extension imports111-`````````````````112-113-Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114-``flask_foo``.115-116-The old form still works, but Flask will issue a117-``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118-way. We also provide a migration utility called `flask-ext-migrate119-<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to120-automatically rewrite your imports for this.121-122-.. _upgrading-to-010:123-124-Version 0.10125-------------126-127-The biggest change going from 0.9 to 0.10 is that the cookie serialization128-format changed from pickle to a specialized JSON format. This change has129-been done in order to avoid the damage an attacker can do if the secret130-key is leaked. When you upgrade you will notice two major changes: all131-sessions that were issued before the upgrade are invalidated and you can132-only store a limited amount of types in the session. The new sessions are133-by design much more restricted to only allow JSON with a few small134-extensions for tuples and strings with HTML markup.135-136-In order to not break people's sessions it is possible to continue using137-the old session system by using the `Flask-OldSessions`_ extension.138-139-Flask also started storing the :data:`flask.g` object on the application140-context instead of the request context. This change should be transparent141-for you but it means that you now can store things on the ``g`` object142-when 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`.145-146-.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147-148-Version 0.9149------------150-151-The behavior of returning tuples from a function was simplified. If you152-return a tuple it no longer defines the arguments for the response object153-you're creating, it's now always a tuple in the form ``(response, status,154-headers)`` where at least one item has to be provided. If you depend on155-the old behavior, you can add it easily by subclassing Flask::156-157- 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)162-163-If you maintain an extension that was using :data:`~flask._request_ctx_stack`164-before, please consider changing to :data:`~flask._app_ctx_stack` if it makes165-sense for your extension. For instance, the app context stack makes sense for166-extensions which connect to databases. Using the app context stack instead of167-the request context stack will make extensions more readily handle use cases168-outside of requests.169-170-Version 0.8171------------172-173-Flask introduced a new session interface system. We also noticed that174-there was a naming collision between ``flask.session`` the module that175-implements sessions and :data:`flask.session` which is the global session176-object. With that introduction we moved the implementation details for177-the session system into a new module called :mod:`flask.sessions`. If you178-used the previously undocumented session support we urge you to upgrade.179-180-If invalid JSON data was submitted Flask will now raise a181-:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the182-default :exc:`ValueError` bubble up. This has the advantage that you no183-longer have to handle that error to avoid an internal server error showing184-up for the user. If you were catching this down explicitly in the past185-as :exc:`ValueError` you will need to change this.186-187-Due to a bug in the test client Flask 0.7 did not trigger teardown188-handlers when the test client was used in a with statement. This was189-since fixed but might require some changes in your test suites if you190-relied on this behavior.191-192-Version 0.7193------------194-195-In Flask 0.7 we cleaned up the code base internally a lot and did some196-backwards incompatible changes that make it easier to implement larger197-applications with Flask. Because we want to make upgrading as easy as198-possible we tried to counter the problems arising from these changes by199-providing a script that can ease the transition.200-201-The script scans your whole application and generates a unified diff with202-changes it assumes are safe to apply. However as this is an automated203-tool it won't be able to find all use cases and it might miss some. We204-internally spread a lot of deprecation warnings all over the place to make205-it easy to find pieces of code that it was unable to upgrade.206-207-We strongly recommend that you hand review the generated patchfile and208-only apply the chunks that look good.209-210-If you are using git as version control system for your project we211-recommend applying the patch with ``path -p1 < patchfile.diff`` and then212-using the interactive commit feature to only apply the chunks that look213-good.214-215-To apply the upgrade script do the following:216-217-1. Download the script: `flask-07-upgrade.py218- <https://raw.githubusercontent.com/pallets/flask/0.12.3/scripts/flask-07-upgrade.py>`_219-2. Run it in the directory of your application::220-221- $ python flask-07-upgrade.py > patchfile.diff222-223-3. Review the generated patchfile.224-4. Apply the patch::225-226- $ patch -p1 < patchfile.diff227-228-5. 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.235-236-Please note that deprecation warnings are disabled by default starting237-with Python 2.7. In order to see the deprecation warnings that might be238-emitted you have to enabled them with the :mod:`warnings` module.239-240-If you are working with windows and you lack the ``patch`` command line241-utility you can get it as part of various Unix runtime environments for242-windows including cygwin, msysgit or ming32. Also source control systems243-like svn, hg or git have builtin support for applying unified diffs as244-generated by the tool. Check the manual of your version control system245-for more information.246-247-Bug in Request Locals248-`````````````````````249-250-Due to a bug in earlier implementations the request local proxies now251-raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they252-are unbound. If you caught these exceptions with :exc:`AttributeError`253-before, you should catch them with :exc:`RuntimeError` now.254-255-Additionally the :func:`~flask.send_file` function is now issuing256-deprecation warnings if you depend on functionality that will be removed257-in Flask 0.11. Previously it was possible to use etags and mimetypes258-when file objects were passed. This was unreliable and caused issues259-for a few setups. If you get a deprecation warning, make sure to260-update your application to work with either filenames there or disable261-etag attaching and attach them yourself.262-263-Old code::264-265- return send_file(my_file_object)266- return send_file(my_file_object)267-268-New code::269-270- return send_file(my_file_object, add_etags=False)271-272-.. _upgrading-to-new-teardown-handling:273-274-Upgrading to new Teardown Handling275-``````````````````````````````````276-277-We streamlined the behavior of the callbacks for request handling. For278-things that modify the response the :meth:`~flask.Flask.after_request`279-decorators continue to work as expected, but for things that absolutely280-must happen at the end of request we introduced the new281-:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that282-change also made after-request work differently under error conditions.283-It's not consistently skipped if exceptions happen whereas previously it284-might have been called twice to ensure it is executed at the end of the285-request.286-287-If you have database connection code that looks like this::288-289- @app.after_request290- def after_request(response):291- g.db.close()292- return response293-294-You are now encouraged to use this instead::295-296- @app.teardown_request297- def after_request(exception):298- if hasattr(g, 'db'):299- g.db.close()300-301-On the upside this change greatly improves the internal code flow and302-makes it easier to customize the dispatching and error handling. This303-makes it now a lot easier to write unit tests as you can prevent closing304-down of database connections for a while. You can take advantage of the305-fact that the teardown callbacks are called when the response context is306-removed from the stack so a test can query the database after request307-handling::308-309- with app.test_client() as client:310- resp = client.get('/')311- # g.db is still bound if there is such a thing312-313- # and here it's gone314-315-Manual Error Handler Attaching316-``````````````````````````````317-318-While it is still possible to attach error handlers to319-:attr:`Flask.error_handlers` it's discouraged to do so and in fact320-deprecated. In general we no longer recommend custom error handler321-attaching via assignments to the underlying dictionary due to the more322-complex internal handling to support arbitrary exception classes and323-blueprints. See :meth:`Flask.errorhandler` for more information.324-325-The proper upgrade is to change this::326-327- app.error_handlers[403] = handle_error328-329-Into this::330-331- app.register_error_handler(403, handle_error)332-333-Alternatively you should just attach the function with a decorator::334-335- @app.errorhandler(403)336- def handle_error(e):337- ...338-339-(Note that :meth:`register_error_handler` is new in Flask 0.7)340-341-Blueprint Support342-`````````````````343-344-Blueprints replace the previous concept of “Modules” in Flask. They345-provide better semantics for various features and work better with large346-applications. The update script provided should be able to upgrade your347-applications automatically, but there might be some cases where it fails348-to upgrade. What changed?349-350-- 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.374-375-If you continue to use the ``Module`` object which is deprecated, Flask will376-restore the previous behavior as good as possible. However we strongly377-recommend upgrading to the new blueprints as they provide a lot of useful378-improvement such as the ability to attach a blueprint multiple times,379-blueprint specific error handlers and a lot more.380-381-382-Version 0.6383------------384-385-Flask 0.6 comes with a backwards incompatible change which affects the386-order of after-request handlers. Previously they were called in the order387-of the registration, now they are called in reverse order. This change388-was made so that Flask behaves more like people expected it to work and389-how other systems handle request pre- and post-processing. If you390-depend on the order of execution of post-request functions, be sure to391-change the order.392-393-Another change that breaks backwards compatibility is that context394-processors will no longer override values passed directly to the template395-rendering function. If for example ``request`` is as variable passed396-directly to the template, the default context processor will not override397-it with the current request object. This makes it easier to extend398-context processors later to inject additional variables without breaking399-existing template not expecting them.400-401-Version 0.5402------------403-404-Flask 0.5 is the first release that comes as a Python package instead of a405-single module. There were a couple of internal refactoring so if you406-depend on undocumented internal details you probably have to adapt the407-imports.408-409-The following changes may be relevant to your application:410-411-- 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.424-425-Version 0.4426------------427-428-For application developers there are no changes that require changes in429-your code. In case you are developing on a Flask extension however, and430-that extension has a unittest-mode you might want to link the activation431-of that mode to the new ``TESTING`` flag.432-433-Version 0.3434------------435-436-Flask 0.3 introduces configuration support and logging as well as437-categories for flashing messages. All these are features that are 100%438-backwards compatible but you might want to take advantage of them.439-440-Configuration Support441-`````````````````````442-443-The configuration support makes it easier to write any kind of application444-that requires some sort of configuration. (Which most likely is the case445-for any application out there).446-447-If you previously had code like this::448-449- app.debug = DEBUG450- app.secret_key = SECRET_KEY451-452-You no longer have to do that, instead you can just load a configuration453-into the config object. How this works is outlined in :ref:`config`.454-455-Logging Integration456-```````````````````457-458-Flask now configures a logger for you with some basic and useful defaults.459-If you run your application in production and want to profit from460-automatic error logging, you might be interested in attaching a proper log461-handler. Also you can start logging warnings and errors into the logger462-when appropriately. For more information on that, read463-:ref:`application-errors`.464-465-Categories for Flash Messages466-`````````````````````````````467-468-Flash messages can now have categories attached. This makes it possible469-to render errors, warnings or regular messages differently for example.470-This is an opt-in feature because it requires some rethinking in the code.471-472-Read all about that in the :ref:`message-flashing-pattern` pattern.modified:src/flask/app.py+5 added-7 removed
189 unmodified lines190 :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 """198 199 #: The class that is used for request objects. See :class:`~flask.Request`200 #: for more information.1822 unmodified lines2023 must return a response. Returning ``None``, or the view ending2024 without returning, is not allowed. The following types are allowed2025 for ``view_rv``:2026 2029- ``str`` (``unicode`` in Python 2)2027+ ``str``2028 A response object is created with the string encoded to UTF-82029 as the body.2030 2033- ``bytes`` (``str`` in Python 2)2031+ ``bytes``2032 A response object is created with the bytes as the body.2033 2034 ``dict``2035 A dictionary that will be jsonify'd before being returned.421 unmodified linesmodified:src/flask/helpers.py+2 added-2 removed
907 unmodified lines908 filename = sys.modules[root_mod_name].__file__909 package_path = os.path.abspath(os.path.dirname(filename))910 911 # 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)916 917 return package_path250 unmodified linesmodified:CHANGES.rst+6 added-9 removed
450 unmodified lines451 Released 2016-05-29, codename Absinthe452 453 - 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 lines566 567 Released 2013-06-13, codename Limoncello568 569 - 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 lines595 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 lines759 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 lines839 - 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 lines856 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.861 862 863 Version 0.6.1864 -------------171 unmodified linesmodified:CONTRIBUTING.rst+3 added-2 removed
133 unmodified lines134 depends on which part of Flask you're working on. Travis-CI will run the full135 suite when you submit your pull request.136 137 The full test suite takes a long time to run because it tests multiple138-combinations of Python and dependencies. You need to have Python 2.7, 3.4,139-3.5, 3.6, 3.7 and PyPy 2.7 installed to run all of the environments. Then run::138+combinations of Python and dependencies. If you don't have a Python139+version installed, it will be skipped with a warning message at the end.140+Run::141 142 tox143 144 Running test coverage53 unmodified lines