Merge pull request #3554 from pallets/drop-python2
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Drop Python 2
authored by David Lord · committed by GitHub · parents 96b4dca, 2ae740d · Browse files · 84 files·+583 added−2049 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
84 files+583 added−2049 removed
- tests:+141 added−271 removed
- other:+442 added−1778 removed
Provenance
- Commit
cd8a374- Tree
6956e6d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
96b4dca- Parent 2
2ae740d
84 files changed+583 added−2049 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/flashing.rst+1 added-1 removed
101 unmodified lines102 103 To flash a message with a different category, just use the second argument104 to the :func:`~flask.flash` function::105 106- flash(u'Invalid password provided', 'error')106+ flash('Invalid password provided', 'error')107 108 Inside the template you then have to tell the109 :func:`~flask.get_flashed_messages` function to also return the110 categories. The loop looks slightly different in that situation then:40 unmodified linesmodified:docs/patterns/lazyloading.rst+1 added-1 removed
91 unmodified lines92 :meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93 name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::94 95 def url(import_name, url_rules=[], **options):96- view = LazyView('yourapplication.' + import_name)96+ view = LazyView(f"yourapplication.{import_name}")97 for url_rule in url_rules:98 app.add_url_rule(url_rule, view_func=view, **options)99 100 # add a single route to the index view9 unmodified linesmodified:docs/patterns/requestchecksum.rst+1 added-1 removed
50 unmodified lines51 # Accessing this parses the input stream52 files = request.files53 # At this point the hash is fully constructed.54 checksum = hash.hexdigest()55- return 'Hash was: %s' % checksum55+ return f"Hash was: {checksum}"modified:docs/patterns/sqlalchemy.rst+8 added-8 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()56 unmodified lines103 104 Querying is simple as well:105 106 >>> User.query.all()107-[<User u'admin'>]107+[<User 'admin'>]108 >>> User.query.filter(User.name == 'admin').first()109-<User u'admin'>109+<User 'admin'>110 111 .. _SQLAlchemy: https://www.sqlalchemy.org/112 .. _declarative:113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/12 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::12 unmodified lines199 200 To query your database, you use the engine directly or use a connection:201 202 >>> users.select(users.c.id == 1).execute().first()203-(1, u'admin', u'admin@localhost')203+(1, 'admin', 'admin@localhost')204 205 These results are also dict-like tuples:206 207 >>> r = users.select(users.c.id == 1).execute().first()208 >>> r['name']209-u'admin'209+'admin'210 211 You can also pass strings of SQL statements to the212 :meth:`~sqlalchemy.engine.base.Connection.execute` method:213 214 >>> engine.execute('select * from users where id = :1', [1]).first()215-(1, u'admin', u'admin@localhost')215+(1, 'admin', 'admin@localhost')216 217 For more information about SQLAlchemy, head over to the218 `website <https://www.sqlalchemy.org/>`_.modified:docs/patterns/streaming.rst+1 added-1 removed
19 unmodified lines20 @app.route('/large.csv')21 def generate_large_csv():22 def generate():23 for row in iter_all_rows():24- yield ','.join(row) + '\n'24+ yield f"{','.join(row)}\n"25 return Response(generate(), mimetype='text/csv')26 27 Each ``yield`` expression is directly sent to the browser. Note though28 that some WSGI middlewares might break streaming, so be careful there in56 unmodified linesmodified:docs/patterns/viewdecorators.rst+1 added-2 removed
140 unmodified lines141 @wraps(f)142 def decorated_function(*args, **kwargs):143 template_name = template144 if template_name is None:145- template_name = request.endpoint \146- .replace('.', '/') + '.html'145+ template_name = f"'{request.endpoint.replace('.', '/')}.html'"146 ctx = f(*args, **kwargs)147 if ctx is None:148 ctx = {}149 elif not isinstance(ctx, dict):22 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/blog.rst+1 added-1 removed
205 unmodified lines206 (id,)207 ).fetchone()208 209 if post is None:210- abort(404, "Post id {0} doesn't exist.".format(id))210+ abort(404, f"Post id {id} doesn't exist.")211 212 if check_author and post['author_id'] != g.user['id']:213 abort(403)214 122 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/tutorial/views.rst+1 added-1 removed
92 unmodified lines93 error = 'Password is required.'94 elif db.execute(95 'SELECT id FROM user WHERE username = ?', (username,)96 ).fetchone() is not None:97- error = 'User {} is already registered.'.format(username)97+ error = f"User {username} is already registered."98 99 if error is None:100 db.execute(101 'INSERT INTO user (username, password) VALUES (?, ?)',200 unmodified linesmodified:docs/api.rst+6 added-6 removed
56 unmodified lines57 In this case the values of the above mentioned attributes would be58 the following:59 60 ============= ======================================================61- `path` ``u'/π/page.html'``62- `full_path` ``u'/π/page.html?x=y'``63- `script_root` ``u'/myapplication'``64- `base_url` ``u'http://www.example.com/myapplication/π/page.html'``65- `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``66- `url_root` ``u'http://www.example.com/myapplication/'``61+ `path` ``'/π/page.html'``62+ `full_path` ``'/π/page.html?x=y'``63+ `script_root` ``'/myapplication'``64+ `base_url` ``'http://www.example.com/myapplication/π/page.html'``65+ `url` ``'http://www.example.com/myapplication/π/page.html?x=y'``66+ `url_root` ``'http://www.example.com/myapplication/'``67 ============= ======================================================68 69 70 .. attribute:: request764 unmodified linesmodified:docs/conf.py+4 added-6 removed
50 unmodified lines51 singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}52 html_static_path = ["_static"]53 html_favicon = "_static/flask-icon.png"54 html_logo = "_static/flask-icon.png"55-html_title = "Flask Documentation ({})".format(version)55+html_title = f"Flask Documentation ({version})"56 html_show_sourcelink = False57 58 # LaTeX ----------------------------------------------------------------59 60-latex_documents = [61- (master_doc, "Flask-{}.tex".format(version), html_title, author, "manual")62-]60+latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")]61 62 # Local Extensions -----------------------------------------------------63 64 8 unmodified lines73 else:74 words = None75 76 if packaging.version.parse(release).is_devrelease:79- url = "{0}master/{1}".format(base_url, text)77+ url = f"{base_url}master/{text}"78 else:81- url = "{0}{1}/{2}".format(base_url, release, text)79+ url = f"{base_url}{release}/{text}"80 81 if words is None:82 words = url83 11 unmodified linesmodified:docs/config.rst+9 added-9 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_KEYS282 unmodified lines595 TESTING = False596 DB_SERVER = '192.168.1.56'597 598 @property599- def DATABASE_URI(self): # Note: all caps600- return 'mysql://user@{}/foo'.format(self.DB_SERVER)599+ def DATABASE_URI(self): # Note: all caps600+ return f"mysql://user@{self.DB_SERVER}/foo"601 602 class ProductionConfig(Config):603 """Uses production database server."""604 DB_SERVER = '192.168.19.32'72 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+6 added-7 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` properly145 unmodified lines446 Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::447 448 >>> from markupsafe import Markup449 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'451- Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')450+ Markup('<strong>Hello <blink>hacker</blink>!</strong>')451 >>> Markup.escape('<blink>hacker</blink>')453- Markup(u'<blink>hacker</blink>')452+ Markup('<blink>hacker</blink>')453 >>> Markup('<em>Marked up</em> » HTML').striptags()455- u'Marked up \xbb HTML'454+ 'Marked up \xbb HTML'455 456 .. versionchanged:: 0.5457 458 Autoescaping is no longer enabled for all templates. The following149 unmodified lines608 609 @app.route('/upload', methods=['GET', 'POST'])610 def upload_file():611 if request.method == 'POST':613- f = request.files['the_file']614- f.save('/var/www/uploads/' + secure_filename(f.filename))612+ file = request.files['the_file']613+ file.save(f"/var/www/uploads/{secure_filename(f.filename)}")614 ...615 616 For some better examples, checkout the :ref:`uploading-files` pattern.617 304 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)modified:docs/templating.rst+2 added-2 removed
220 unmodified lines221 functions)::222 223 @app.context_processor224 def utility_processor():225- def format_price(amount, currency=u'€'):226- return u'{0:.2f}{1}'.format(amount, currency)225+ def format_price(amount, currency="€"):226+ return f"{amount:.2f}{currency}"227 return dict(format_price=format_price)228 229 The context processor above makes the `format_price` function available to all230 templates::6 unmodified linesmodified:docs/testing.rst+6 added-3 removed
163 unmodified lines164 165 def test_login_logout(client):166 """Make sure login and logout works."""167 168- rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])168+ username = flaskr.app.config["USERNAME"]169+ password = flaskr.app.config["PASSWORD"]170+171+ rv = login(client, username, password)172 assert b'You were logged in' in rv.data173 174 rv = logout(client)175 assert b'You were logged out' in rv.data176 174- rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])177+ rv = login(client, f"{username}x", password)178 assert b'Invalid username' in rv.data179 177- rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')180+ rv = login(client, username, f'{password}x')181 assert b'Invalid password' in rv.data182 183 Test Adding Messages184 --------------------280 unmodified linesdeleted: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:examples/javascript/js_example/__init__.py+1 added-1 removed
1 from flask import Flask2 3 app = Flask(__name__)4 5-from js_example import views5+from js_example import views # noqa: F401modified:examples/javascript/js_example/views.py+1 added-1 removed
6 unmodified lines7 8 @app.route("/", defaults={"js": "plain"})9 @app.route("/<any(plain, jquery, fetch):js>")10 def index(js):11- return render_template("{0}.html".format(js), js=js)11+ return render_template(f"{js}.html", js=js)12 13 14 @app.route("/add", methods=["POST"])15 def add():3 unmodified linesmodified:examples/javascript/setup.py+1 added-3 removed
1-import io2-1 from setuptools import find_packages2 from setuptools import setup3 6-with io.open("README.rst", "rt", encoding="utf8") as f:4+with open("README.rst", encoding="utf8") as f:5 readme = f.read()6 7 setup(8 name="js_example",13 unmodified linesmodified:examples/tutorial/flaskr/auth.py+1 added-1 removed
62 unmodified lines63 elif (64 db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()65 is not None66 ):67- error = "User {0} is already registered.".format(username)67+ error = f"User {username} is already registered."68 69 if error is None:70 # the name is available, store it in the database and go to71 # the login page45 unmodified linesmodified:examples/tutorial/flaskr/blog.py+1 added-1 removed
47 unmodified lines48 .fetchone()49 )50 51 if post is None:52- abort(404, "Post id {0} doesn't exist.".format(id))52+ abort(404, f"Post id {id} doesn't exist.")53 54 if check_author and post["author_id"] != g.user["id"]:55 abort(403)56 69 unmodified linesmodified:examples/tutorial/tests/conftest.py+1 added-1 removed
42 unmodified lines43 """A test runner for the app's Click commands."""44 return app.test_cli_runner()45 46 47-class AuthActions(object):47+class AuthActions:48 def __init__(self, client):49 self._client = client50 51 def login(self, username="test", password="test"):11 unmodified linesmodified:examples/tutorial/tests/test_db.py+1 added-1 removed
15 unmodified lines16 assert "closed" in str(e.value)17 18 19 def test_init_db_command(runner, monkeypatch):20- class Recorder(object):20+ class Recorder:21 called = False22 23 def fake_init_db():24 Recorder.called = True5 unmodified linesmodified:examples/tutorial/setup.py+1 added-3 removed
1-import io2-1 from setuptools import find_packages2 from setuptools import setup3 6-with io.open("README.rst", "rt", encoding="utf8") as f:4+with open("README.rst", encoding="utf8") as f:5 readme = f.read()6 7 setup(8 name="flaskr",13 unmodified linesmodified:src/flask/json/__init__.py+10 added-13 removed
1-# -*- coding: utf-8 -*-1 """2 flask.json3 ~~~~~~~~~~4 9 unmodified lines14 from itsdangerous import json as _json15 from jinja2 import Markup16 from werkzeug.http import http_date17 19-from .._compat import PY220-from .._compat import text_type18 from ..globals import current_app19 from ..globals import request20 21 try:22 import dataclasses23 except ImportError:24+ # Python < 3.725 dataclasses = None26 27 # Figure out if simplejson escapes slashes. This behavior was changed28 # from one version to another without reason.64 unmodified lines93 return str(o)94 if dataclasses and dataclasses.is_dataclass(o):95 return dataclasses.asdict(o)96 if hasattr(o, "__html__"):99- return text_type(o.__html__())97+ return str(o.__html__())98 return _json.JSONEncoder.default(self, o)99 100 101 class JSONDecoder(_json.JSONDecoder):104 unmodified lines206 """207 _dump_arg_defaults(kwargs, app=app)208 encoding = kwargs.pop("encoding", None)209 rv = _json.dumps(obj, **kwargs)212- if encoding is not None and isinstance(rv, text_type):210+ if encoding is not None and isinstance(rv, str):211 rv = rv.encode(encoding)212 return rv213 214 38 unmodified lines253 254 def load(fp, app=None, **kwargs):255 """Like :func:`loads` but reads from a file object."""256 _load_arg_defaults(kwargs, app=app)259- if not PY2:260- fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")257+ fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")258 return _json.load(fp, **kwargs)259 260 261 def htmlsafe_dumps(obj, **kwargs):22 unmodified lines284 filter. Alternatively use ``|tojson|forceescape``.285 """286 rv = (287 dumps(obj, **kwargs)291- .replace(u"<", u"\\u003c")292- .replace(u">", u"\\u003e")293- .replace(u"&", u"\\u0026")294- .replace(u"'", u"\\u0027")288+ .replace("<", "\\u003c")289+ .replace(">", "\\u003e")290+ .replace("&", "\\u0026")291+ .replace("'", "\\u0027")292 )293 if not _slash_escape:294 rv = rv.replace("\\/", "/")295 return rv296 297 298 def htmlsafe_dump(obj, fp, **kwargs):299 """Like :func:`htmlsafe_dumps` but writes into a file object."""303- fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))300+ fp.write(str(htmlsafe_dumps(obj, **kwargs)))301 302 303 def jsonify(*args, **kwargs):304 """This function wraps :func:`dumps` to add a few enhancements that make58 unmodified lines363 else:364 data = args or kwargs365 366 return current_app.response_class(370- dumps(data, indent=indent, separators=separators) + "\n",367+ f"{dumps(data, indent=indent, separators=separators)}\n",368 mimetype=current_app.config["JSONIFY_MIMETYPE"],369 )370 371 2 unmodified linesmodified:src/flask/json/tag.py+6 added-9 removed
1-# -*- coding: utf-8 -*-1 """2 Tagged JSON3 ~~~~~~~~~~~4 43 unmodified lines48 from jinja2 import Markup49 from werkzeug.http import http_date50 from werkzeug.http import parse_date51 53-from .._compat import iteritems54-from .._compat import text_type52 from ..json import dumps53 from ..json import loads54 55 59-class JSONTag(object):56+class JSONTag:57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""58 59 __slots__ = ("serializer",)60 43 unmodified lines104 )105 106 def to_json(self, value):107 key = next(iter(value))111- return {key + "__": self.serializer.tag(value[key])}108+ return {f"{key}__": self.serializer.tag(value[key])}109 110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}7 unmodified lines120 121 def to_json(self, value):122 # JSON objects may only have string keys, so don't bother tagging the123 # key here.127- return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))124+ return {k: self.serializer.tag(v) for k, v in value.items()}125 126 tag = to_json127 128 48 unmodified lines177 def check(self, value):178 return callable(getattr(value, "__html__", None))179 180 def to_json(self, value):184- return text_type(value.__html__())181+ return str(value.__html__())182 183 def to_python(self, value):184 return Markup(value)185 25 unmodified lines211 def to_python(self, value):212 return parse_date(value)213 214 218-class TaggedJSONSerializer(object):215+class TaggedJSONSerializer:216 """Serializer that uses a tag system to compactly represent objects that217 are not JSON types. Passed as the intermediate serializer to218 :class:`itsdangerous.Serializer`.219 47 unmodified lines267 key = tag.key268 269 if key is not None:270 if not force and key in self.tags:274- raise KeyError("Tag '{0}' is already registered.".format(key))271+ raise KeyError(f"Tag '{key}' is already registered.")272 273 self.tags[key] = tag274 275 if index is None:31 unmodified linesmodified:src/flask/__init__.py+1 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask3 ~~~~~4 10 unmodified lines15 from werkzeug.exceptions import abort16 from werkzeug.utils import redirect17 18 from . import json20-from ._compat import json_available19 from .app import Flask20 from .app import Request21 from .app import Response22 from .blueprints import Blueprint31 unmodified lines54 from .signals import template_rendered55 from .templating import render_template56 from .templating import render_template_string57 60-__version__ = "1.2.0.dev"58+__version__ = "2.0.0.dev"modified:src/flask/__main__.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask.__main__3 ~~~~~~~~~~~~~~4 10 unmodified linesdeleted:src/flask/_compat.py-145 removed
1-# -*- coding: utf-8 -*-2-"""3- flask._compat4- ~~~~~~~~~~~~~5-6- Some py2/py3 compatibility support based on a stripped down7- version of six so we don't have to depend on a specific version8- of it.9-10- :copyright: 2010 Pallets11- :license: BSD-3-Clause12-"""13-import sys14-15-PY2 = sys.version_info[0] == 216-_identity = lambda x: x17-18-try: # Python 219- text_type = unicode20- string_types = (str, unicode)21- integer_types = (int, long)22-except NameError: # Python 323- text_type = str24- string_types = (str,)25- integer_types = (int,)26-27-if not PY2:28- iterkeys = lambda d: iter(d.keys())29- itervalues = lambda d: iter(d.values())30- iteritems = lambda d: iter(d.items())31-32- from inspect import getfullargspec as getargspec33- from io import StringIO34- import collections.abc as collections_abc35-36- def reraise(tp, value, tb=None):37- if value.__traceback__ is not tb:38- raise value.with_traceback(tb)39- raise value40-41- implements_to_string = _identity42-43-else:44- iterkeys = lambda d: d.iterkeys()45- itervalues = lambda d: d.itervalues()46- iteritems = lambda d: d.iteritems()47-48- from inspect import getargspec49- from cStringIO import StringIO50- import collections as collections_abc51-52- exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")53-54- def implements_to_string(cls):55- cls.__unicode__ = cls.__str__56- cls.__str__ = lambda x: x.__unicode__().encode("utf-8")57- return cls58-59-60-def with_metaclass(meta, *bases):61- """Create a base class with a metaclass."""62- # This requires a bit of explanation: the basic idea is to make a63- # dummy metaclass for one level of class instantiation that replaces64- # itself with the actual metaclass.65- class metaclass(type):66- def __new__(metacls, name, this_bases, d):67- return meta(name, bases, d)68-69- return type.__new__(metaclass, "temporary_class", (), {})70-71-72-# Certain versions of pypy have a bug where clearing the exception stack73-# breaks the __exit__ function in a very peculiar way. The second level of74-# exception blocks is necessary because pypy seems to forget to check if an75-# exception happened until the next bytecode instruction?76-#77-# Relevant PyPy bugfix commit:78-# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330179-# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later80-# versions.81-#82-# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.83-BROKEN_PYPY_CTXMGR_EXIT = False84-if hasattr(sys, "pypy_version_info"):85-86- class _Mgr(object):87- def __enter__(self):88- return self89-90- def __exit__(self, *args):91- if hasattr(sys, "exc_clear"):92- # Python 3 (PyPy3) doesn't have exc_clear93- sys.exc_clear()94-95- try:96- try:97- with _Mgr():98- raise AssertionError()99- except: # noqa: B001100- # We intentionally use a bare except here. See the comment above101- # regarding a pypy bug as to why.102- raise103- except TypeError:104- BROKEN_PYPY_CTXMGR_EXIT = True105- except AssertionError:106- pass107-108-109-try:110- from os import fspath111-except ImportError:112- # Backwards compatibility as proposed in PEP 0519:113- # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility114- def fspath(path):115- return path.__fspath__() if hasattr(path, "__fspath__") else path116-117-118-class _DeprecatedBool(object):119- def __init__(self, name, version, value):120- self.message = "'{}' is deprecated and will be removed in version {}.".format(121- name, version122- )123- self.value = value124-125- def _warn(self):126- import warnings127-128- warnings.warn(self.message, DeprecationWarning, stacklevel=2)129-130- def __eq__(self, other):131- self._warn()132- return other == self.value133-134- def __ne__(self, other):135- self._warn()136- return other != self.value137-138- def __bool__(self):139- self._warn()140- return self.value141-142- __nonzero__ = __bool__143-144-145-json_available = _DeprecatedBool("flask.json_available", "2.0.0", True)modified:src/flask/app.py+64 added-142 removed
1-# -*- coding: utf-8 -*-1 """2 flask.app3 ~~~~~~~~~4 3 unmodified lines8 :license: BSD-3-Clause9 """10 import os11 import sys13-import warnings12 from datetime import timedelta13 from functools import update_wrapper14 from itertools import chain15 from threading import Lock13 unmodified lines29 from werkzeug.wrappers import BaseResponse30 31 from . import cli32 from . import json35-from ._compat import integer_types36-from ._compat import reraise37-from ._compat import string_types38-from ._compat import text_type33 from .config import Config34 from .config import ConfigAttribute35 from .ctx import _AppCtxGlobals36 from .ctx import AppContext147 unmodified lines184 :param instance_relative_config: if set to ``True`` relative filenames185 for loading the config are assumed to186 be relative to the instance path instead187 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.188+ :param root_path: The path to the root of the application files.189+ This should only be set manually when it can't be detected190+ automatically, such as for namespace packages.191 """192 193 #: The class that is used for request objects. See :class:`~flask.Request`194 #: for more information.389 unmodified lines584 assert (585 bool(static_host) == host_matching586 ), "Invalid static_host/host_matching combination"587 self.add_url_rule(596- self.static_url_path + "/<path:filename>",588+ f"{self.static_url_path}/<path:filename>",589 endpoint="static",590 host=static_host,591 view_func=self.send_static_file,592 )117 unmodified lines710 """711 prefix, package_path = find_package(self.import_name)712 if prefix is None:713 return os.path.join(package_path, "instance")722- return os.path.join(prefix, "var", self.name + "-instance")714+ return os.path.join(prefix, "var", f"{self.name}-instance")715 716 def open_instance_resource(self, resource, mode="rb"):717 """Opens a resource from the application's instance folder718 (:attr:`instance_path`). Otherwise works like340 unmodified lines1059 from .testing import FlaskCliRunner as cls1060 1061 return cls(self, **kwargs)1062 1071- def open_session(self, request):1072- """Creates or opens a new session. Default implementation stores all1073- session data in a signed cookie. This requires that the1074- :attr:`secret_key` is set. Instead of overriding this method1075- we recommend replacing the :class:`session_interface`.1076-1077- .. deprecated: 1.01078- Will be removed in 2.0. Use1079- ``session_interface.open_session`` instead.1080-1081- :param request: an instance of :attr:`request_class`.1082- """1083-1084- warnings.warn(1085- DeprecationWarning(1086- '"open_session" is deprecated and will be removed in'1087- ' 2.0. Use "session_interface.open_session" instead.'1088- )1089- )1090- return self.session_interface.open_session(self, request)1091-1092- def save_session(self, session, response):1093- """Saves the session if it needs updates. For the default1094- implementation, check :meth:`open_session`. Instead of overriding this1095- method we recommend replacing the :class:`session_interface`.1096-1097- .. deprecated: 1.01098- Will be removed in 2.0. Use1099- ``session_interface.save_session`` instead.1100-1101- :param session: the session to be saved (a1102- :class:`~werkzeug.contrib.securecookie.SecureCookie`1103- object)1104- :param response: an instance of :attr:`response_class`1105- """1106-1107- warnings.warn(1108- DeprecationWarning(1109- '"save_session" is deprecated and will be removed in'1110- ' 2.0. Use "session_interface.save_session" instead.'1111- )1112- )1113- return self.session_interface.save_session(self, session, response)1114-1115- def make_null_session(self):1116- """Creates a new instance of a missing session. Instead of overriding1117- this method we recommend replacing the :class:`session_interface`.1118-1119- .. deprecated: 1.01120- Will be removed in 2.0. Use1121- ``session_interface.make_null_session`` instead.1122-1123- .. versionadded:: 0.71124- """1125-1126- warnings.warn(1127- DeprecationWarning(1128- '"make_null_session" is deprecated and will be removed'1129- ' in 2.0. Use "session_interface.make_null_session"'1130- " instead."1131- )1132- )1133- return self.session_interface.make_null_session(self)1134-1063 @setupmethod1064 def register_blueprint(self, blueprint, **options):1065 """Register a :class:`~flask.Blueprint` on the application. Keyword1066 arguments passed to this method will override the defaults set on the16 unmodified lines1083 first_registration = False1084 1085 if blueprint.name in self.blueprints:1086 assert self.blueprints[blueprint.name] is blueprint, (1159- "A name collision occurred between blueprints %r and %r. Both"1160- ' share the same name "%s". Blueprints that are created on the'1161- " fly need unique names."1162- % (blueprint, self.blueprints[blueprint.name], blueprint.name)1087+ "A name collision occurred between blueprints"1088+ f" {blueprint!r} and {self.blueprints[blueprint.name]!r}."1089+ f" Both share the same name {blueprint.name!r}."1090+ f" Blueprints that are created on the fly need unique"1091+ f" names."1092 )1093 else:1094 self.blueprints[blueprint.name] = blueprint1095 self._blueprint_order.append(blueprint)14 unmodified lines1110 rule,1111 endpoint=None,1112 view_func=None,1113 provide_automatic_options=None,1185- **options1114+ **options,1115 ):1116 """Connects a URL rule. Works exactly like the :meth:`route`1117 decorator. If a view_func is provided it will be registered with the1118 endpoint.55 unmodified lines1174 # methods we can use that instead. If neither exists, we go with1175 # a tuple of only ``GET`` as default.1176 if methods is None:1177 methods = getattr(view_func, "methods", None) or ("GET",)1249- if isinstance(methods, string_types):1178+ if isinstance(methods, str):1179 raise TypeError(1251- "Allowed methods have to be iterables of strings, "1252- 'for example: @app.route(..., methods=["POST"])'1180+ "Allowed methods must be a list of strings, for"1181+ ' example: @app.route(..., methods=["POST"])'1182 )1254- methods = set(item.upper() for item in methods)1183+ methods = {item.upper() for item in methods}1184 1185 # Methods that should always be added1186 required_methods = set(getattr(view_func, "required_methods", ()))1187 21 unmodified lines1209 if view_func is not None:1210 old_func = self.view_functions.get(endpoint)1211 if old_func is not None and old_func != view_func:1212 raise AssertionError(1284- "View function mapping is overwriting an "1285- "existing endpoint function: %s" % endpoint1213+ "View function mapping is overwriting an existing"1214+ f" endpoint function: {endpoint}"1215 )1216 self.view_functions[endpoint] = view_func1217 1218 def route(self, rule, **options):54 unmodified lines1273 1274 :param exc_class_or_code: Any exception class, or an HTTP status1275 code as an integer.1276 """1348- if isinstance(exc_class_or_code, integer_types):1277+ if isinstance(exc_class_or_code, int):1278 exc_class = default_exceptions[exc_class_or_code]1279 else:1280 exc_class = exc_class_or_code1281 59 unmodified lines1341 :type f: callable1342 """1343 if isinstance(code_or_exception, HTTPException): # old broken behavior1344 raise ValueError(1416- "Tried to register a handler for an exception instance {0!r}."1417- " Handlers can only be registered for exception classes or"1418- " HTTP error codes.".format(code_or_exception)1345+ "Tried to register a handler for an exception instance"1346+ f" {code_or_exception!r}. Handlers can only be"1347+ " registered for exception classes or HTTP error codes."1348 )1349 1350 try:1351 exc_class, code = self._get_exc_class_and_code(code_or_exception)1352 except KeyError:1353 raise KeyError(1425- "'{0}' is not a recognized HTTP error code. Use a subclass of"1426- " HTTPException with that code instead.".format(code_or_exception)1354+ f"'{code_or_exception}' is not a recognized HTTP error"1355+ " code. Use a subclass of HTTPException with that code"1356+ " instead."1357 )1358 1359 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1360 handlers[exc_class] = f362 unmodified lines1723 message.1724 1725 .. versionadded:: 0.71726 """1797- exc_type, exc_value, tb = sys.exc_info()1798- assert exc_value is e1799- # ensure not to trash sys.exc_info() at that point in case someone1800- # wants the traceback preserved in handle_http_exception. Of course1801- # we cannot prevent users from trashing it themselves in a custom1802- # trap_http_exception method so that's their fault then.1803-1727 if isinstance(e, BadRequestKeyError):1728 if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1729 e.show_exception = True1730 1731 # Werkzeug < 0.15 doesn't add the KeyError to the 4001732 # message, add it in manually.1733 # TODO: clean up once Werkzeug >= 0.15.5 is required1734 if e.args[0] not in e.get_description():1812- e.description = "KeyError: '{}'".format(*e.args)1735+ e.description = f"KeyError: {e.args[0]!r}"1736 elif not hasattr(BadRequestKeyError, "show_exception"):1737 e.args = ()1738 1739 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1 unmodified line1741 1742 handler = self._find_error_handler(e)1743 1744 if handler is None:1822- reraise(exc_type, exc_value, tb)1745+ raise1746+1747 return handler(e)1748 1749 def handle_exception(self, e):1750 """Handle an exception that did not have an error handler28 unmodified lines1779 even for the default 500 response when there is no handler.1780 1781 .. versionadded:: 0.31782 """1859- exc_type, exc_value, tb = sys.exc_info()1783+ exc_info = sys.exc_info()1784 got_request_exception.send(self, exception=e)1785 1786 if self.propagate_exceptions:1863- # if we want to repropagate the exception, we can attempt to1864- # raise it with the whole traceback in case we can do that1865- # (the function was actually called from the except part)1866- # otherwise, we just raise the error again1867- if exc_value is e:1868- reraise(exc_type, exc_value, tb)1869- else:1870- raise e1787+ # Re-raise if called with an active exception, otherwise1788+ # raise the passed in exception.1789+ if exc_info[1] is e:1790+ raise1791 1872- self.log_exception((exc_type, exc_value, tb))1792+ raise e1793+1794+ self.log_exception(exc_info)1795 server_error = InternalServerError()1796 # TODO: pass as param when Werkzeug>=1.0.0 is required1797 # TODO: also remove note about this from docstring and docs1798 server_error.original_exception = e12 unmodified lines1811 1812 .. versionadded:: 0.81813 """1814 self.logger.error(1893- "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info1815+ f"Exception on {request.path} [{request.method}]", exc_info=exc_info1816 )1817 1818 def raise_routing_exception(self, request):1819 """Exceptions that are recording during routing are reraised with127 unmodified lines1947 must return a response. Returning ``None``, or the view ending1948 without returning, is not allowed. The following types are allowed1949 for ``view_rv``:1950 2029- ``str`` (``unicode`` in Python 2)1951+ ``str``1952 A response object is created with the string encoded to UTF-81953 as the body.1954 2033- ``bytes`` (``str`` in Python 2)1955+ ``bytes``1956 A response object is created with the bytes as the body.1957 1958 ``dict``1959 A dictionary that will be jsonify'd before being returned.47 unmodified lines2007 2008 # the body must not be None2009 if rv is None:2010 raise TypeError(2089- 'The view function for "{}" did not return a valid response. The'2090- " function either returned None or ended without a return"2091- " statement.".format(request.endpoint)2011+ f"The view function for {request.endpoint!r} did not"2012+ " return a valid response. The function either returned"2013+ " None or ended without a return statement."2014 )2015 2016 # make sure the body is an instance of the response class2017 if not isinstance(rv, self.response_class):2096- if isinstance(rv, (text_type, bytes, bytearray)):2018+ if isinstance(rv, (str, bytes, bytearray)):2019 # let the response class set the status and headers instead of2020 # waiting to do it manually, so that the class can handle any2021 # special logic2022 rv = self.response_class(rv, status=status, headers=headers)5 unmodified lines2028 # class to the correct type2029 try:2030 rv = self.response_class.force_type(rv, request.environ)2031 except TypeError as e:2110- new_error = TypeError(2111- "{e}\nThe view function did not return a valid"2112- " response. The return type must be a string, dict, tuple,"2113- " Response instance, or WSGI callable, but it was a"2114- " {rv.__class__.__name__}.".format(e=e, rv=rv)2115- )2116- reraise(TypeError, new_error, sys.exc_info()[2])2032+ raise TypeError(2033+ f"{e}\nThe view function did not return a valid"2034+ " response. The return type must be a string,"2035+ " dict, tuple, Response instance, or WSGI"2036+ f" callable, but it was a {type(rv).__name__}."2037+ ).with_traceback(sys.exc_info()[2])2038 else:2039 raise TypeError(2040 "The view function did not return a valid"2120- " response. The return type must be a string, dict, tuple,"2121- " Response instance, or WSGI callable, but it was a"2122- " {rv.__class__.__name__}.".format(rv=rv)2041+ " response. The return type must be a string,"2042+ " dict, tuple, Response instance, or WSGI"2043+ f" callable, but it was a {type(rv).__name__}."2044 )2045 2046 # prefer the status if it was provided2047 if status is not None:2127- if isinstance(status, (text_type, bytes, bytearray)):2048+ if isinstance(status, (str, bytes, bytearray)):2049 rv.status = status2050 else:2051 rv.status_code = status2052 55 unmodified lines2108 for func in funcs:2109 func(endpoint, values)2110 2111 def handle_url_build_error(self, error, endpoint, values):2191- """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.2112+ """Handle :class:`~werkzeug.routing.BuildError` on2113+ :meth:`url_for`.2114 """2193- exc_type, exc_value, tb = sys.exc_info()2115 for handler in self.url_build_error_handlers:2116 try:2117 rv = handler(error, endpoint, values)2197- if rv is not None:2198- return rv2118 except BuildError as e:2200- # make error available outside except block (py3)2119+ # make error available outside except block2120 error = e2121+ else:2122+ if rv is not None:2123+ return rv2124 2203- # At this point we want to reraise the exception. If the error is2204- # still the same one we can reraise it with the original traceback,2205- # otherwise we raise it from here.2206- if error is exc_value:2207- reraise(exc_type, exc_value, tb)2125+ # Re-raise if called with an active exception, otherwise raise2126+ # the passed in exception.2127+ if error is sys.exc_info()[1]:2128+ raise2129+2130 raise error2131 2132 def preprocess_request(self):2133 """Called before the request is dispatched. Calls242 unmodified lines2376 wrapped to applying middleware."""2377 return self.wsgi_app(environ, start_response)2378 2379 def __repr__(self):2458- return "<%s %r>" % (self.__class__.__name__, self.name)2380+ return f"<{type(self).__name__} {self.name!r}>"modified:src/flask/blueprints.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 flask.blueprints3 ~~~~~~~~~~~~~~~~4 11 unmodified lines16 # a singleton sentinel value for parameter defaults17 _sentinel = object()18 19 21-class BlueprintSetupState(object):20+class BlueprintSetupState:21 """Temporary holder object for registering a blueprint with the22 application. An instance of this class is created by the23 :meth:`~flask.Blueprint.make_setup_state` method and later passed24 to all register callback functions.53 unmodified lines78 if "defaults" in options:79 defaults = dict(defaults, **options.pop("defaults"))80 self.app.add_url_rule(81 rule,83- "%s.%s" % (self.blueprint.name, endpoint),82+ f"{self.blueprint.name}.{endpoint}",83 view_func,84 defaults=defaults,86- **options85+ **options,86 )87 88 89 class Blueprint(_PackageBoundObject):155 unmodified lines245 state = self.make_setup_state(app, options, first_registration)246 247 if self.has_static_folder:248 state.add_url_rule(250- self.static_url_path + "/<path:filename>",249+ f"{self.static_url_path}/<path:filename>",250 view_func=self.send_static_file,251 endpoint="static",252 )253 315 unmodified linesmodified:src/flask/cli.py+49 added-74 removed
1-# -*- coding: utf-8 -*-1 """2 flask.cli3 ~~~~~~~~~4 1 unmodified line6 7 :copyright: 2010 Pallets8 :license: BSD-3-Clause9 """11-from __future__ import print_function12-10 import ast11 import inspect12 import os13 import platform7 unmodified lines21 22 import click23 from werkzeug.utils import import_string24 28-from ._compat import getargspec29-from ._compat import itervalues30-from ._compat import reraise31-from ._compat import text_type25 from .globals import current_app26 from .helpers import get_debug_flag27 from .helpers import get_env28 from .helpers import get_load_dotenv26 unmodified lines55 if isinstance(app, Flask):56 return app57 58 # Otherwise find the only object that is a Flask instance.66- matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)]59+ matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]60 61 if len(matches) == 1:62 return matches[0]63 elif len(matches) > 1:64 raise NoAppException(72- 'Detected multiple Flask applications in module "{module}". Use '73- '"FLASK_APP={module}:name" to specify the correct '74- "one.".format(module=module.__name__)65+ "Detected multiple Flask applications in module"66+ f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"67+ f" to specify the correct one."68 )69 70 # Search for app factory functions.78- for attr_name in ("create_app", "make_app"):71+ for attr_name in {"create_app", "make_app"}:72 app_factory = getattr(module, attr_name, None)73 74 if inspect.isfunction(app_factory):75 try:4 unmodified lines80 except TypeError:81 if not _called_with_wrong_args(app_factory):82 raise83 raise NoAppException(91- 'Detected factory "{factory}" in module "{module}", but '92- "could not call it without arguments. Use "93- "\"FLASK_APP='{module}:{factory}(args)'\" to specify "94- "arguments.".format(factory=attr_name, module=module.__name__)84+ f"Detected factory {attr_name!r} in module {module.__name__!r},"85+ " but could not call it without arguments. Use"86+ f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""87+ " to specify arguments."88 )89 90 raise NoAppException(98- 'Failed to find Flask application or factory in module "{module}". '99- 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__)91+ "Failed to find Flask application or factory in module"92+ f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"93+ " to specify one."94 )95 96 97 def call_factory(script_info, app_factory, arguments=()):98 """Takes an app factory, a ``script_info` object and optionally a tuple99 of arguments. Checks for the existence of a script_info argument and calls100 the app_factory depending on that and the arguments provided.101 """108- args_spec = getargspec(app_factory)102+ args_spec = inspect.getfullargspec(app_factory)103 arg_names = args_spec.args104 arg_defaults = args_spec.defaults105 106 if "script_info" in arg_names:43 unmodified lines150 match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)151 152 if not match:153 raise NoAppException(160- '"{name}" is not a valid variable name or function '161- "expression.".format(name=app_name)154+ f"{app_name!r} is not a valid variable name or function expression."155 )156 157 name, args = match.groups()158 4 unmodified lines163 164 if inspect.isfunction(attr):165 if args:166 try:174- args = ast.literal_eval("({args},)".format(args=args))175- except (ValueError, SyntaxError) as e:176- raise NoAppException(177- "Could not parse the arguments in "178- '"{app_name}".'.format(e=e, app_name=app_name)179- )167+ args = ast.literal_eval(f"({args},)")168+ except (ValueError, SyntaxError):169+ raise NoAppException(f"Could not parse the arguments in {app_name!r}.")170 else:171 args = ()172 173 try:2 unmodified lines176 if not _called_with_wrong_args(attr):177 raise178 179 raise NoAppException(190- '{e}\nThe factory "{app_name}" in module "{module}" could not '191- "be called with the specified arguments.".format(192- e=e, app_name=app_name, module=module.__name__193- )180+ f"{e}\nThe factory {app_name!r} in module"181+ f" {module.__name__!r} could not be called with the"182+ " specified arguments."183 )184 else:185 app = attr186 187 if isinstance(app, Flask):188 return app189 190 raise NoAppException(202- "A valid Flask application was not obtained from "203- '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name)191+ "A valid Flask application was not obtained from"192+ f" '{module.__name__}:{app_name}'."193 )194 195 196 def prepare_import(path):32 unmodified lines229 __import__(module_name)230 except ImportError:231 # Reraise the ImportError if it occurred within the imported module.232 # Determine this by checking whether the trace has a depth > 1.244- if sys.exc_info()[-1].tb_next:233+ if sys.exc_info()[2].tb_next:234 raise NoAppException(246- 'While importing "{name}", an ImportError was raised:'247- "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())235+ f"While importing {module_name!r}, an ImportError was"236+ f" raised:\n\n{traceback.format_exc()}"237 )238 elif raise_if_not_found:250- raise NoAppException('Could not import "{name}".'.format(name=module_name))239+ raise NoAppException(f"Could not import {module_name!r}.")240 else:241 return242 243 module = sys.modules[module_name]10 unmodified lines254 255 import werkzeug256 from . import __version__257 269- message = "Python %(python)s\nFlask %(flask)s\nWerkzeug %(werkzeug)s"258 click.echo(271- message272- % {273- "python": platform.python_version(),274- "flask": __version__,275- "werkzeug": werkzeug.__version__,276- },259+ f"Python {platform.python_version()}\n"260+ f"Flask {__version__}\n"261+ f"Werkzeug {werkzeug.__version__}",262 color=ctx.color,263 )264 ctx.exit()265 7 unmodified lines273 is_eager=True,274 )275 276 292-class DispatchingApp(object):277+class DispatchingApp:278 """Special application that dispatches to a Flask application which279 is imported by name in a background thread. If an error happens280 it is recorded and shown as part of the WSGI handling which in case281 of the Werkzeug debugger means that it shows up in the browser.29 unmodified lines311 __traceback_hide__ = True # noqa: F841312 exc_info = self._bg_loading_exc_info313 if exc_info is not None:314 self._bg_loading_exc_info = None330- reraise(*exc_info)315+ raise exc_info316 317 def _load_unlocked(self):318 __traceback_hide__ = True # noqa: F841319 self._app = rv = self.loader()12 unmodified lines332 rv = self._load_unlocked()333 return rv(environ, start_response)334 335 351-class ScriptInfo(object):336+class ScriptInfo:337 """Helper object to deal with Flask applications. This is usually not338 necessary to interface with as it's used internally in the dispatching339 to click. In future versions of Flask this object will most likely play340 a bigger role. Typically it's created automatically by the138 unmodified lines479 create_app=None,480 add_version_option=True,481 load_dotenv=True,482 set_debug_flag=True,498- **extra483+ **extra,484 ):485 params = list(extra.pop("params", None) or ())486 487 if add_version_option:83 unmodified lines571 )572 573 kwargs["obj"] = obj574 kwargs.setdefault("auto_envvar_prefix", "FLASK")590- return super(FlaskGroup, self).main(*args, **kwargs)575+ return super().main(*args, **kwargs)576 577 578 def _path_is_ancestor(path, other):579 """Take ``other`` and remove the length of ``path`` from it. Then join it70 unmodified lines650 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":651 return652 653 if app_import_path is not None:669- message = ' * Serving Flask app "{0}"'.format(app_import_path)654+ message = f" * Serving Flask app {app_import_path!r}"655 656 if not eager_loading:657 message += " (lazy loading)"658 659 click.echo(message)660 676- click.echo(" * Environment: {0}".format(env))661+ click.echo(f" * Environment: {env}")662 663 if env == "production":664 click.secho(680- " WARNING: This is a development server. "681- "Do not use it in a production deployment.",665+ " WARNING: This is a development server. Do not use it in"666+ " a production deployment.",667 fg="red",668 )669 click.secho(" Use a production WSGI server instead.", dim=True)670 671 if debug is not None:687- click.echo(" * Debug mode: {0}".format("on" if debug else "off"))672+ click.echo(f" * Debug mode: {'on' if debug else 'off'}")673 674 675 class CertParamType(click.ParamType):676 """Click option type for the ``--cert`` option. Allows either an32 unmodified lines709 return value710 711 obj = import_string(value, silent=True)712 728- if sys.version_info < (2, 7, 9):729- if obj:730- return obj731- else:732- if isinstance(obj, ssl.SSLContext):733- return obj713+ if isinstance(obj, ssl.SSLContext):714+ return obj715 716 raise717 718 2 unmodified lines721 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.722 """723 cert = ctx.params.get("cert")724 is_adhoc = cert == "adhoc"725+ is_context = ssl and isinstance(cert, ssl.SSLContext)726 745- if sys.version_info < (2, 7, 9):746- is_context = cert and not isinstance(cert, (text_type, bytes))747- else:748- is_context = ssl and isinstance(cert, ssl.SSLContext)749-727 if value is not None:728 if is_adhoc:729 raise click.BadParameter(730 'When "--cert" is "adhoc", "--key" is not used.', ctx, param23 unmodified lines754 """755 756 def convert(self, value, param, ctx):757 items = self.split_envvar_value(value)781- super_convert = super(SeparatedPathType, self).convert758+ super_convert = super().convert759 return [super_convert(item, param, ctx) for item in items]760 761 762 @click.command("run", short_help="Run a development server.")37 unmodified lines800 default=None,801 type=SeparatedPathType(),802 help=(803 "Extra files that trigger a reload on change. Multiple paths"827- " are separated by '{}'.".format(os.path.pathsep)804+ f" are separated by {os.path.pathsep!r}."805 ),806 )807 @pass_script_info808 def run_command(45 unmodified lines854 import code855 from .globals import _app_ctx_stack856 857 app = _app_ctx_stack.top.app881- banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (882- sys.version,883- sys.platform,884- app.import_name,885- app.env,886- app.instance_path,858+ banner = (859+ f"Python {sys.version} on {sys.platform}\n"860+ f"App: {app.import_name} [{app.env}]\n"861+ f"Instance: {app.instance_path}"862 )863 ctx = {}864 865 # Support the regular Python interpreter startup script if someone866 # is using it.867 startup = os.environ.get("PYTHONSTARTUP")868 if startup and os.path.isfile(startup):894- with open(startup, "r") as f:869+ with open(startup) as f:870 eval(compile(f.read(), startup, "exec"), ctx)871 872 ctx.update(app.make_shell_context())873 76 unmodified linesmodified:src/flask/config.py+13 added-41 removed
1-# -*- coding: utf-8 -*-1 """2 flask.config3 ~~~~~~~~~~~~4 4 unmodified lines9 """10 import errno11 import os12 import types14-import warnings13 14 from werkzeug.utils import import_string15 18-from ._compat import iteritems19-from ._compat import string_types16 21-22-class ConfigAttribute(object):17+class ConfigAttribute:18 """Makes an attribute forward to the config"""19 20 def __init__(self, name, get_converter=None):21 self.__name__ = name75 unmodified lines97 if not rv:98 if silent:99 return False100 raise RuntimeError(106- "The environment variable %r is not set "107- "and as such configuration could not be "108- "loaded. Set this variable and make it "109- "point to a configuration file" % variable_name101+ f"The environment variable {variable_name!r} is not set"102+ " and as such configuration could not be loaded. Set"103+ " this variable and make it point to a configuration"104+ " file"105 )106 return self.from_pyfile(rv, silent=silent)107 108 def from_pyfile(self, filename, silent=False):15 unmodified lines124 d.__file__ = filename125 try:126 with open(filename, mode="rb") as config_file:127 exec(compile(config_file.read(), filename, "exec"), d.__dict__)133- except IOError as e:128+ except OSError as e:129 if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):130 return False136- e.strerror = "Unable to load configuration file (%s)" % e.strerror131+ e.strerror = f"Unable to load configuration file ({e.strerror})"132 raise133 self.from_object(d)134 return True135 28 unmodified lines164 using :meth:`from_object`.165 166 :param obj: an import name or object167 """173- if isinstance(obj, string_types):168+ if isinstance(obj, str):169 obj = import_string(obj)170 for key in dir(obj):171 if key.isupper():172 self[key] = getattr(obj, key)22 unmodified lines195 196 try:197 with open(filename) as f:198 obj = load(f)204- except IOError as e:199+ except OSError as e:200 if silent and e.errno in (errno.ENOENT, errno.EISDIR):201 return False202 208- e.strerror = "Unable to load configuration file (%s)" % e.strerror203+ e.strerror = f"Unable to load configuration file ({e.strerror})"204 raise205 206 return self.from_mapping(obj)207 213- def from_json(self, filename, silent=False):214- """Update the values in the config from a JSON file. The loaded215- data is passed to the :meth:`from_mapping` method.216-217- :param filename: The path to the JSON file. This can be an218- absolute path or relative to the config root path.219- :param silent: Ignore the file if it doesn't exist.220-221- .. deprecated:: 2.0222- Use :meth:`from_file` with :meth:`json.load` instead.223-224- .. versionadded:: 0.11225- """226- warnings.warn(227- "'from_json' is deprecated and will be removed in 2.0."228- " Use 'from_file(filename, load=json.load)' instead.",229- DeprecationWarning,230- stacklevel=2,231- )232- from .json import load233-234- return self.from_file(filename, load, silent=silent)235-208 def from_mapping(self, *mapping, **kwargs):209 """Updates the config like :meth:`update` ignoring items with non-upper210 keys.211 6 unmodified lines218 else:219 mappings.append(mapping[0])220 elif len(mapping) > 1:221 raise TypeError(250- "expected at most 1 positional argument, got %d" % len(mapping)222+ f"expected at most 1 positional argument, got {len(mapping)}"223 )224 mappings.append(kwargs.items())225 for mapping in mappings:226 for (key, value) in mapping:29 unmodified lines256 257 .. versionadded:: 0.11258 """259 rv = {}288- for k, v in iteritems(self):260+ for k, v in self.items():261 if not k.startswith(namespace):262 continue263 if trim_namespace:264 key = k[len(namespace) :]4 unmodified lines269 rv[key] = v270 return rv271 272 def __repr__(self):301- return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))273+ return f"<{type(self).__name__} {dict.__repr__(self)}>"modified:src/flask/ctx.py+12 added-36 removed
1-# -*- coding: utf-8 -*-1 """2 flask.ctx3 ~~~~~~~~~4 6 unmodified lines11 from functools import update_wrapper12 13 from werkzeug.exceptions import HTTPException14 16-from ._compat import BROKEN_PYPY_CTXMGR_EXIT17-from ._compat import reraise15 from .globals import _app_ctx_stack16 from .globals import _request_ctx_stack17 from .signals import appcontext_popped18 from .signals import appcontext_pushed2 unmodified lines21 # a singleton sentinel value for parameter defaults22 _sentinel = object()23 24 28-class _AppCtxGlobals(object):25+class _AppCtxGlobals:26 """A plain object. Used as a namespace for storing data during an27 application context.28 29 Creating an app context automatically creates this object, which is57 unmodified lines87 88 def __repr__(self):89 top = _app_ctx_stack.top90 if top is not None:94- return "<flask.g of %r>" % top.app.name91+ return f"<flask.g of {top.app.name!r}>"92 return object.__repr__(self)93 94 95 def after_this_request(f):102 unmodified lines198 """199 return _app_ctx_stack.top is not None200 201 205-class AppContext(object):202+class AppContext:203 """The application context binds an application object implicitly204 to the current thread or greenlet, similar to how the205 :class:`RequestContext` binds request information. The application206 context is also implicitly created if a request context is created12 unmodified lines219 220 def push(self):221 """Binds the app context to the current context."""222 self._refcnt += 1226- if hasattr(sys, "exc_clear"):227- sys.exc_clear()223 _app_ctx_stack.push(self)224 appcontext_pushed.send(self.app)225 226 def pop(self, exc=_sentinel):5 unmodified lines232 exc = sys.exc_info()[1]233 self.app.do_teardown_appcontext(exc)234 finally:235 rv = _app_ctx_stack.pop()241- assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)236+ assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"237 appcontext_popped.send(self.app)238 239 def __enter__(self):240 self.push()1 unmodified line242 243 def __exit__(self, exc_type, exc_value, tb):244 self.pop(exc_value)245 251- if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:252- reraise(exc_type, exc_value, tb)246 254-255-class RequestContext(object):247+class RequestContext:248 """The request context contains all request relevant information. It is249 created at the beginning of the request and pushed to the250 `_request_ctx_stack` and removed at the end of it. It will create the251 URL adapter and request object for the WSGI environment provided.115 unmodified lines367 self._implicit_app_ctx_stack.append(app_ctx)368 else:369 self._implicit_app_ctx_stack.append(None)370 379- if hasattr(sys, "exc_clear"):380- sys.exc_clear()381-371 _request_ctx_stack.push(self)372 373 # Open the session at the moment that the request context is available.374 # This allows a custom open_session method to use the request context.17 unmodified lines392 .. versionchanged:: 0.9393 Added the `exc` argument.394 """395 app_ctx = self._implicit_app_ctx_stack.pop()396+ clear_request = False397 398 try:409- clear_request = False399 if not self._implicit_app_ctx_stack:400 self.preserved = False401 self._preserved_exc = None402 if exc is _sentinel:403 exc = sys.exc_info()[1]404 self.app.do_teardown_request(exc)405 417- # If this interpreter supports clearing the exception information418- # we do that now. This will only go into effect on Python 2.x,419- # on 3.x it disappears automatically at the end of the exception420- # stack.421- if hasattr(sys, "exc_clear"):422- sys.exc_clear()423-406 request_close = getattr(self.request, "close", None)407 if request_close is not None:408 request_close()409 clear_request = True8 unmodified lines418 # Get rid of the app as well if necessary.419 if app_ctx is not None:420 app_ctx.pop(exc)421 440- assert rv is self, "Popped wrong request context. (%r instead of %r)" % (441- rv,442- self,443- )422+ assert (423+ rv is self424+ ), f"Popped wrong request context. ({rv!r} instead of {self!r})"425 426 def auto_pop(self, exc):427 if self.request.environ.get("flask._preserve_context") or (428 exc is not None and self.app.preserve_context_on_exception14 unmodified lines443 # the context can be force kept alive for the test client.444 # See flask.testing for how this works.445 self.auto_pop(exc_value)446 466- if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:467- reraise(exc_type, exc_value, tb)468-447 def __repr__(self):470- return "<%s '%s' [%s] of %s>" % (471- self.__class__.__name__,472- self.request.url,473- self.request.method,474- self.app.name,448+ return (449+ f"<{type(self).__name__} {self.request.url!r}"450+ f" [{self.request.method}] of {self.app.name}>"451 )modified:src/flask/debughelpers.py+38 added-42 removed
1-# -*- coding: utf-8 -*-1 """2 flask.debughelpers3 ~~~~~~~~~~~~~~~~~~4 4 unmodified lines9 """10 import os11 from warnings import warn12 14-from ._compat import implements_to_string15-from ._compat import text_type13 from .app import Flask14 from .blueprints import Blueprint15 from .globals import _request_ctx_stack16 3 unmodified lines20 unexpected unicode or binary data.21 """22 23 27-@implements_to_string24 class DebugFilesKeyError(KeyError, AssertionError):25 """Raised from request.files during debugging. The idea is that it can26 provide a better error message than just a generic KeyError/BadRequest.27 """28 29 def __init__(self, request, key):30 form_matches = request.form.getlist(key)31 buf = [36- 'You tried to access the file "%s" in the request.files '37- "dictionary but it does not exist. The mimetype for the request "38- 'is "%s" instead of "multipart/form-data" which means that no '39- "file contents were transmitted. To fix this error you should "40- 'provide enctype="multipart/form-data" in your form.'41- % (key, request.mimetype)32+ f"You tried to access the file {key!r} in the request.files"33+ " dictionary but it does not exist. The mimetype for the"34+ f" request is {request.mimetype!r} instead of"35+ " 'multipart/form-data' which means that no file contents"36+ " were transmitted. To fix this error you should provide"37+ ' enctype="multipart/form-data" in your form.'38 ]39 if form_matches:40+ names = ", ".join(repr(x) for x in form_matches)41 buf.append(42 "\n\nThe browser instead transmitted some file names. "46- "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)43+ f"This was submitted: {names}"44 )45 self.msg = "".join(buf)46 47 def __str__(self):8 unmodified lines56 57 def __init__(self, request):58 exc = request.routing_exception59 buf = [63- "A request was sent to this URL (%s) but a redirect was "64- 'issued automatically by the routing system to "%s".'65- % (request.url, exc.new_url)60+ f"A request was sent to this URL ({request.url}) but a"61+ " redirect was issued automatically by the routing system"62+ f" to {exc.new_url!r}."63 ]64 65 # In case just a slash was appended we can be extra helpful69- if request.base_url + "/" == exc.new_url.split("?")[0]:66+ if f"{request.base_url}/" == exc.new_url.split("?")[0]:67 buf.append(71- " The URL was defined with a trailing slash so "72- "Flask will automatically redirect to the URL "73- "with the trailing slash if it was accessed "74- "without one."68+ " The URL was defined with a trailing slash so Flask"69+ " will automatically redirect to the URL with the"70+ " trailing slash if it was accessed without one."71 )72 73 buf.append(78- " Make sure to directly send your %s-request to this URL "79- "since we can't make browsers or HTTP clients redirect "80- "with form data reliably or without user interaction." % request.method74+ " Make sure to directly send your"75+ f" {request.method}-request to this URL since we can't make"76+ " browsers or HTTP clients redirect with form data reliably"77+ " or without user interaction."78 )79 buf.append("\n\nNote: this exception is only raised in debug mode")80 AssertionError.__init__(self, "".join(buf).encode("utf-8"))81 19 unmodified lines101 request.files.__class__ = newcls102 103 104 def _dump_loader_info(loader):108- yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)105+ yield f"class: {type(loader).__module__}.{type(loader).__name__}"106 for key, value in sorted(loader.__dict__.items()):107 if key.startswith("_"):108 continue109 if isinstance(value, (tuple, list)):113- if not all(isinstance(x, (str, text_type)) for x in value):110+ if not all(isinstance(x, str) for x in value):111 continue115- yield "%s:" % key112+ yield f"{key}:"113 for item in value:117- yield " - %s" % item114+ yield f" - {item}"115 continue119- elif not isinstance(value, (str, text_type, int, float, bool)):116+ elif not isinstance(value, (str, int, float, bool)):117 continue121- yield "%s: %r" % (key, value)118+ yield f"{key}: {value!r}"119 120 121 def explain_template_loading_attempts(app, template, attempts):122 """This should help developers understand what failed"""126- info = ['Locating template "%s":' % template]123+ info = [f"Locating template {template!r}:"]124 total_found = 0125 blueprint = None126 reqctx = _request_ctx_stack.top127 if reqctx is not None and reqctx.request.blueprint is not None:128 blueprint = reqctx.request.blueprint129 130 for idx, (loader, srcobj, triple) in enumerate(attempts):131 if isinstance(srcobj, Flask):135- src_info = 'application "%s"' % srcobj.import_name132+ src_info = f"application {srcobj.import_name!r}"133 elif isinstance(srcobj, Blueprint):137- src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)134+ src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"135 else:136 src_info = repr(srcobj)137 141- info.append("% 5d: trying loader of %s" % (idx + 1, src_info))138+ info.append(f"{idx + 1:5}: trying loader of {src_info}")139 140 for line in _dump_loader_info(loader):144- info.append(" %s" % line)141+ info.append(f" {line}")142 143 if triple is None:144 detail = "no match"145 else:149- detail = "found (%r)" % (triple[1] or "<string>")146+ detail = f"found ({triple[1] or '<string>'!r})"147 total_found += 1151- info.append(" -> %s" % detail)148+ info.append(f" -> {detail}")149 150 seems_fishy = False151 if total_found == 0:152 info.append("Error: the template could not be found.")3 unmodified lines156 seems_fishy = True157 158 if blueprint is not None and seems_fishy:159 info.append(163- " The template was looked up from an endpoint that "164- 'belongs to the blueprint "%s".' % blueprint160+ " The template was looked up from an endpoint that belongs"161+ f" to the blueprint {blueprint!r}."162 )163 info.append(" Maybe you did not place a template in the right folder?")164 info.append(" See https://flask.palletsprojects.com/blueprints/#templates")165 3 unmodified lines169 def explain_ignored_app_run():170 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":171 warn(172 Warning(176- "Silently ignoring app.run() because the "177- "application is run from the flask command line "178- "executable. Consider putting app.run() behind an "179- 'if __name__ == "__main__" guard to silence this '180- "warning."173+ "Silently ignoring app.run() because the application is"174+ " run from the flask command line executable. Consider"175+ ' putting app.run() behind an if __name__ == "__main__"'176+ " guard to silence this warning."177 ),178 stacklevel=3,179 )modified:src/flask/globals.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask.globals3 ~~~~~~~~~~~~~4 57 unmodified linesmodified:src/flask/helpers.py+57 added-91 removed
1-# -*- coding: utf-8 -*-1 """2 flask.helpers3 ~~~~~~~~~~~~~4 23 unmodified lines28 from werkzeug.routing import BuildError29 from werkzeug.urls import url_quote30 from werkzeug.wsgi import wrap_file31 33-from ._compat import fspath34-from ._compat import PY235-from ._compat import string_types36-from ._compat import text_type32 from .globals import _app_ctx_stack33 from .globals import _request_ctx_stack34 from .globals import current_app35 from .globals import request117 unmodified lines153 # iterator in we're still running the cleanup logic. Generators154 # don't need that because they are closed on their destruction155 # automatically.156 try:162- for item in gen:163- yield item157+ yield from gen158 finally:159 if hasattr(gen, "close"):160 gen.close()161 148 unmodified lines310 blueprint_name = request.blueprint311 312 if endpoint[:1] == ".":313 if blueprint_name is not None:320- endpoint = blueprint_name + endpoint314+ endpoint = f"{blueprint_name}{endpoint}"315 else:316 endpoint = endpoint[1:]317 318 external = values.pop("_external", False)44 unmodified lines363 values["_scheme"] = scheme364 return appctx.app.handle_url_build_error(error, endpoint, values)365 366 if anchor is not None:373- rv += "#" + url_quote(anchor)367+ rv += f"#{url_quote(anchor)}"368 return rv369 370 371 def get_template_attribute(template_name, attribute):197 unmodified lines569 mtime = None570 fsize = None571 572 if hasattr(filename_or_fp, "__fspath__"):579- filename_or_fp = fspath(filename_or_fp)573+ filename_or_fp = os.fspath(filename_or_fp)574 581- if isinstance(filename_or_fp, string_types):575+ if isinstance(filename_or_fp, str):576 filename = filename_or_fp577 if not os.path.isabs(filename):578 filename = os.path.join(current_app.root_path, filename)579 file = None21 unmodified lines601 if as_attachment:602 if attachment_filename is None:603 raise TypeError("filename unavailable, required for sending as attachment")604 611- if not isinstance(attachment_filename, text_type):605+ if not isinstance(attachment_filename, str):606 attachment_filename = attachment_filename.decode("utf-8")607 608 try:609 attachment_filename = attachment_filename.encode("ascii")610 except UnicodeEncodeError:611+ quoted = url_quote(attachment_filename, safe="")612 filenames = {613 "filename": unicodedata.normalize("NFKD", attachment_filename).encode(614 "ascii", "ignore"615 ),621- "filename*": "UTF-8''%s" % url_quote(attachment_filename, safe=b""),616+ "filename*": f"UTF-8''{quoted}",617 }618 else:619 filenames = {"filename": attachment_filename}620 11 unmodified lines632 file = open(filename, "rb")633 mtime = os.path.getmtime(filename)634 fsize = os.path.getsize(filename)635 elif isinstance(file, io.BytesIO):641- try:642- fsize = file.getbuffer().nbytes636+ fsize = file.getbuffer().nbytes643- except AttributeError:644- # Python 2 doesn't have getbuffer645- fsize = len(file.getvalue())637 elif isinstance(file, io.TextIOBase):638 raise ValueError("Files must be opened in binary mode or use BytesIO.")639 640 data = wrap_file(request.environ, file)20 unmodified lines661 if add_etags and filename is not None:662 from warnings import warn663 664 try:674- rv.set_etag(675- "%s-%s-%s"676- % (677- os.path.getmtime(filename),678- os.path.getsize(filename),679- adler32(680- filename.encode("utf-8")681- if isinstance(filename, text_type)682- else filename683- )684- & 0xFFFFFFFF,665+ check = (666+ adler32(667+ filename.encode("utf-8") if isinstance(filename, str) else filename668 )669+ & 0xFFFFFFFF670 )671+ rv.set_etag(672+ f"{os.path.getmtime(filename)}-{os.path.getsize(filename)}-{check}"673+ )674 except OSError:675 warn(689- "Access %s failed, maybe it does not exist, so ignore etags in "690- "headers" % filename,676+ f"Access {filename} failed, maybe it does not exist, so"677+ " ignore etags in headers",678 stacklevel=2,679 )680 681 if conditional:73 unmodified lines755 download.756 :param options: optional keyword arguments that are directly757 forwarded to :func:`send_file`.758 """772- filename = fspath(filename)773- directory = fspath(directory)759+ filename = os.fspath(filename)760+ directory = os.fspath(directory)761 filename = safe_join(directory, filename)762 if not os.path.isabs(filename):763 filename = os.path.join(current_app.root_path, filename)764 try:24 unmodified lines789 # current working directory.790 if loader is None or import_name == "__main__":791 return os.getcwd()792 806- # For .egg, zipimporter does not have get_filename until Python 2.7.807- # Some other loaders might exhibit the same behavior.793 if hasattr(loader, "get_filename"):794 filepath = loader.get_filename(import_name)795 else:796 # Fall back to imports.5 unmodified lines802 # namespace package. In this case we pick the root path from the803 # first module that is contained in our package.804 if filepath is None:805 raise RuntimeError(821- "No root path can be found for the provided "822- 'module "%s". This can happen because the '823- "module came from an import hook that does "824- "not provide file name information or because "825- "it's a namespace package. In this case "826- "the root path needs to be explicitly "827- "provided." % import_name806+ "No root path can be found for the provided module"807+ f" {import_name!r}. This can happen because the module"808+ " came from an import hook that does not provide file"809+ " name information or because it's a namespace package."810+ " In this case the root path needs to be explicitly"811+ " provided."812 )813 814 # filepath is import_name.py for a module, or __init__.py for a package.815 return os.path.dirname(os.path.abspath(filepath))2 unmodified lines818 def _matching_loader_thinks_module_is_package(loader, mod_name):819 """Given the loader that loaded a module and the module this function820 attempts to figure out if the given module is actually a package.821 """822+ cls = type(loader)823 # If the loader can tell us if something is a package, we can824 # directly ask the loader.825 if hasattr(loader, "is_package"):826 return loader.is_package(mod_name)827 # importlib's namespace loaders do not have this functionality but828 # all the modules it loads are packages, so we can take advantage of829 # this information.845- elif (846- loader.__class__.__module__ == "_frozen_importlib"847- and loader.__class__.__name__ == "NamespaceLoader"848- ):830+ elif cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":831 return True832 # Otherwise we need to fail with an error that explains what went833 # wrong.834 raise AttributeError(853- (854- "%s.is_package() method is missing but is required by Flask of "855- "PEP 302 import hooks. If you do not use import hooks and "856- "you encounter this error please file a bug against Flask."857- )858- % loader.__class__.__name__835+ f"{cls.__name__}.is_package() method is missing but is required"836+ " for PEP 302 import hooks."837 )838 839 840 def _find_package_path(root_mod_name):841 """Find the path where the module's root exists in"""864- if sys.version_info >= (3, 4):865- import importlib.util842+ import importlib.util843 867- try:868- spec = importlib.util.find_spec(root_mod_name)869- if spec is None:870- raise ValueError("not found")871- # ImportError: the machinery told us it does not exist872- # ValueError:873- # - the module name was invalid874- # - the module name is __main__875- # - *we* raised `ValueError` due to `spec` being `None`876- except (ImportError, ValueError):877- pass # handled below844+ try:845+ spec = importlib.util.find_spec(root_mod_name)846+ if spec is None:847+ raise ValueError("not found")848+ # ImportError: the machinery told us it does not exist849+ # ValueError:850+ # - the module name was invalid851+ # - the module name is __main__852+ # - *we* raised `ValueError` due to `spec` being `None`853+ except (ImportError, ValueError):854+ pass # handled below855+ else:856+ # namespace package857+ if spec.origin in {"namespace", None}:858+ return os.path.dirname(next(iter(spec.submodule_search_locations)))859+ # a package (with __init__.py)860+ elif spec.submodule_search_locations:861+ return os.path.dirname(os.path.dirname(spec.origin))862+ # just a normal module863 else:879- # namespace package880- if spec.origin in {"namespace", None}:881- return os.path.dirname(next(iter(spec.submodule_search_locations)))882- # a package (with __init__.py)883- elif spec.submodule_search_locations:884- return os.path.dirname(os.path.dirname(spec.origin))885- # just a normal module886- else:887- return os.path.dirname(spec.origin)864+ return os.path.dirname(spec.origin)865 866 # we were unable to find the `package_path` using PEP 451 loaders867 loader = pkgutil.get_loader(root_mod_name)868 if loader is None or root_mod_name == "__main__":869 # import name is not found, or interactive/main module870 return os.getcwd()871 else:895- # For .egg, zipimporter does not have get_filename until Python 2.7.872 if hasattr(loader, "get_filename"):873 filename = loader.get_filename(root_mod_name)874 elif hasattr(loader, "archive"):875 # zipimporter's loader.archive points to the .egg or .zip8 unmodified lines884 filename = sys.modules[root_mod_name].__file__885 package_path = os.path.abspath(os.path.dirname(filename))886 887 # 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.888+ # rightmost part. This needs to go through a helper function889+ # because of namespace packages.890 if _matching_loader_thinks_module_is_package(loader, root_mod_name):891 package_path = os.path.dirname(package_path)892 893 return package_path26 unmodified lines920 return base_dir, package_path921 return None, package_path922 923 948-class locked_cached_property(object):924+class locked_cached_property:925 """A decorator that converts a function into a lazy property. The926 function wrapped is called the first time to retrieve the result927 and then that calculated result is used the next time you access928 the value. Works like the one in Werkzeug but has a lock for17 unmodified lines946 obj.__dict__[self.__name__] = value947 return value948 949 974-class _PackageBoundObject(object):950+class _PackageBoundObject:951 #: The name of the package or module that this app belongs to. Do not952 #: change this once it is set by the constructor.953 import_name = None954 48 unmodified lines1003 return self._static_url_path1004 1005 if self.static_folder is not None:1006 basename = os.path.basename(self.static_folder)1031- return ("/" + basename).rstrip("/")1007+ return f"/{basename}".rstrip("/")1008 1009 @static_url_path.setter1010 def static_url_path(self, value):1011 if value is not None:103 unmodified lines1115 1116 def is_ip(value):1117 """Determine if the given string is an IP address.1118 1143- Python 2 on Windows doesn't provide ``inet_pton``, so this only1144- checks IPv4 addresses in that environment.1145-1119 :param value: value to check1120 :type value: str1121 1122 :return: True if string is an IP address1123 :rtype: bool1124 """1152- if PY2 and os.name == "nt":1153- try:1154- socket.inet_aton(value)1155- return True1156- except socket.error:1157- return False1158-1125 for family in (socket.AF_INET, socket.AF_INET6):1126 try:1127 socket.inet_pton(family, value)1162- except socket.error:1128+ except OSError:1129 pass1130 else:1131 return True1132 1 unmodified linemodified:src/flask/logging.py-32 removed
1-# -*- coding: utf-8 -*-1 """2 flask.logging3 ~~~~~~~~~~~~~4 5 :copyright: 2010 Pallets6 :license: BSD-3-Clause7 """9-from __future__ import absolute_import10-8 import logging9 import sys13-import warnings10 11 from werkzeug.local import LocalProxy12 13 from .globals import request38 unmodified lines52 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")53 )54 55 60-def _has_config(logger):61- """Decide if a logger has direct configuration applied by checking62- its properties against the defaults.63-64- :param logger: The :class:`~logging.Logger` to inspect.65- """66- return (67- logger.level != logging.NOTSET68- or logger.handlers69- or logger.filters70- or not logger.propagate71- )72-73-56 def create_logger(app):57 """Get the Flask app's logger and configure it if needed.58 59 The logger name will be the same as7 unmodified lines67 :func:`~flask.logging.wsgi_errors_stream` with a basic format.68 """69 logger = logging.getLogger(app.name)70 89- # 1.1.0 changes name of logger, warn if config is detected for old90- # name and not new name91- for old_name in ("flask.app", "flask"):92- old_logger = logging.getLogger(old_name)93-94- if _has_config(old_logger) and not _has_config(logger):95- warnings.warn(96- "'app.logger' is named '{name}' for this application,"97- " but configuration was found for '{old_name}', which"98- " no longer has an effect. The logging configuration"99- " should be moved to '{name}'.".format(name=app.name, old_name=old_name)100- )101- break102-71 if app.debug and not logger.level:72 logger.setLevel(logging.DEBUG)73 74 if not has_level_handler(logger):3 unmodified linesmodified:src/flask/sessions.py+14 added-15 removed
1-# -*- coding: utf-8 -*-1 """2 flask.sessions3 ~~~~~~~~~~~~~~4 3 unmodified lines8 :license: BSD-3-Clause9 """10 import hashlib11 import warnings12+from collections.abc import MutableMapping13 from datetime import datetime14 15 from itsdangerous import BadSignature16 from itsdangerous import URLSafeTimedSerializer17 from werkzeug.datastructures import CallbackDict18 19-from ._compat import collections_abc19 from .helpers import is_ip20 from .helpers import total_seconds21 from .json.tag import TaggedJSONSerializer22 23 25-class SessionMixin(collections_abc.MutableMapping):24+class SessionMixin(MutableMapping):25 """Expands a basic dictionary with session attributes."""26 27 @property28 def permanent(self):46 unmodified lines75 def on_update(self):76 self.modified = True77 self.accessed = True78 80- super(SecureCookieSession, self).__init__(initial, on_update)79+ super().__init__(initial, on_update)80 81 def __getitem__(self, key):82 self.accessed = True84- return super(SecureCookieSession, self).__getitem__(key)83+ return super().__getitem__(key)84 85 def get(self, key, default=None):86 self.accessed = True88- return super(SecureCookieSession, self).get(key, default)87+ return super().get(key, default)88 89 def setdefault(self, key, default=None):90 self.accessed = True92- return super(SecureCookieSession, self).setdefault(key, default)91+ return super().setdefault(key, default)92 93 94 class NullSession(SecureCookieSession):95 """Class used to generate nicer error messages if sessions are not11 unmodified lines107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109 110 112-class SessionInterface(object):111+class SessionInterface:112 """The basic interface you have to implement in order to replace the113 default session interface which uses werkzeug's securecookie114 implementation. The only methods you have to implement are115 :meth:`open_session` and :meth:`save_session`, the others have91 unmodified lines207 # remove any leading '.' since we'll add that later208 rv = rv.rsplit(":", 1)[0].lstrip(".")209 210 if "." not in rv:212- # Chrome doesn't allow names without a '.'213- # this should only come up with localhost214- # hack around this by not setting the name, and show a warning211+ # Chrome doesn't allow names without a '.'. This should only212+ # come up with localhost. Hack around this by not setting213+ # the name, and show a warning.214 warnings.warn(216- '"{rv}" is not a valid cookie domain, it must contain a ".".'217- " Add an entry to your hosts file, for example"218- ' "{rv}.localdomain", and use that instead.'.format(rv=rv)215+ f"{rv!r} is not a valid cookie domain, it must contain"216+ " a '.'. Add an entry to your hosts file, for example"217+ f" '{rv}.localdomain', and use that instead."218 )219 app.config["SESSION_COOKIE_DOMAIN"] = False220 return None221 9 unmodified lines231 232 # if this is not an ip and app is mounted at the root, allow subdomain233 # matching by adding a '.' prefix234 if self.get_cookie_path(app) == "/" and not ip:236- rv = "." + rv235+ rv = f".{rv}"236 237 app.config["SESSION_COOKIE_DOMAIN"] = rv238 return rv239 154 unmodified linesmodified:src/flask/signals.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask.signals3 ~~~~~~~~~~~~~4 9 unmodified lines14 signals_available = True15 except ImportError:16 signals_available = False17 19- class Namespace(object):18+ class Namespace:19 def signal(self, name, doc=None):20 return _FakeSignal(name, doc)21 23- class _FakeSignal(object):22+ class _FakeSignal:23 """If blinker is unavailable, create a fake class with the same24 interface that allows sending of signals but will fail with an25 error on anything else. Instead of doing anything on send, it26 will just ignore the arguments and do nothing instead.38 unmodified linesmodified:src/flask/templating.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask.templating3 ~~~~~~~~~~~~~~~~4 150 unmodified linesmodified:src/flask/testing.py+10 added-30 removed
1-# -*- coding: utf-8 -*-1 """2 flask.testing3 ~~~~~~~~~~~~~4 2 unmodified lines7 8 :copyright: 2010 Pallets9 :license: BSD-3-Clause10 """12-import warnings11 from contextlib import contextmanager12 13 import werkzeug.test14 from click.testing import CliRunner34 unmodified lines49 base_url=None,50 subdomain=None,51 url_scheme=None,52 *args,55- **kwargs53+ **kwargs,54 ):55 assert not (base_url or subdomain or url_scheme) or (56 base_url is not None57 ) != bool(4 unmodified lines62 http_host = app.config.get("SERVER_NAME") or "localhost"63 app_root = app.config["APPLICATION_ROOT"]64 65 if subdomain:68- http_host = "{0}.{1}".format(subdomain, http_host)66+ http_host = f"{subdomain}.{http_host}"67 68 if url_scheme is None:69 url_scheme = app.config["PREFERRED_URL_SCHEME"]70 71 url = url_parse(path)74- base_url = "{scheme}://{netloc}/{path}".format(75- scheme=url.scheme or url_scheme,76- netloc=url.netloc or http_host,77- path=app_root.lstrip("/"),72+ base_url = (73+ f"{url.scheme or url_scheme}://{url.netloc or http_host}"74+ f"/{app_root.lstrip('/')}"75 )76 path = url.path77 78 if url.query:79 sep = b"?" if isinstance(url.query, bytes) else "?"80 path += sep + url.query81 82 self.app = app86- super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)83+ super().__init__(path, base_url, *args, **kwargs)84 85 def json_dumps(self, obj, **kwargs):86 """Serialize ``obj`` to a JSON-formatted string.87 3 unmodified lines91 kwargs.setdefault("app", self.app)92 return json_dumps(obj, **kwargs)93 94 98-def make_test_environ_builder(*args, **kwargs):99- """Create a :class:`flask.testing.EnvironBuilder`.100-101- .. deprecated: 1.1102- Will be removed in 2.0. Construct103- ``flask.testing.EnvironBuilder`` directly instead.104- """105- warnings.warn(106- DeprecationWarning(107- '"make_test_environ_builder()" is deprecated and will be'108- ' removed in 2.0. Construct "flask.testing.EnvironBuilder"'109- " directly instead."110- )111- )112- return EnvironBuilder(*args, **kwargs)113-114-95 class FlaskClient(Client):96 """Works like a regular Werkzeug test client but has some knowledge about97 how Flask works to defer the cleanup of the request context stack to the98 end of a ``with`` body when used in a ``with`` statement. For general10 unmodified lines109 110 preserve_context = False111 112 def __init__(self, *args, **kwargs):133- super(FlaskClient, self).__init__(*args, **kwargs)113+ super().__init__(*args, **kwargs)114 self.environ_base = {115 "REMOTE_ADDR": "127.0.0.1",136- "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,116+ "HTTP_USER_AGENT": f"werkzeug/{werkzeug.__version__}",117 }118 119 @contextmanager120 def session_transaction(self, *args, **kwargs):115 unmodified lines236 """237 238 def __init__(self, app, **kwargs):239 self.app = app260- super(FlaskCliRunner, self).__init__(**kwargs)240+ super().__init__(**kwargs)241 242 def invoke(self, cli=None, args=None, **kwargs):243 """Invokes a CLI command in an isolated environment. See244 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for14 unmodified lines259 260 if "obj" not in kwargs:261 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)262 283- return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)263+ return super().invoke(cli, args, **kwargs)modified:src/flask/views.py+5 added-7 removed
1-# -*- coding: utf-8 -*-1 """2 flask.views3 ~~~~~~~~~~~4 1 unmodified line6 7 :copyright: 2010 Pallets8 :license: BSD-3-Clause9 """11-from ._compat import with_metaclass10 from .globals import request11 12 13 http_method_funcs = frozenset(14 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]15 )16 17 20-class View(object):18+class View:19 """Alternative way to use view functions. A subclass has to implement20 :meth:`dispatch_request` which is called with the view arguments from21 the URL routing system. If :attr:`methods` is provided the methods22 do not have to be passed to the :meth:`~flask.Flask.add_url_rule`2 unmodified lines25 class MyView(View):26 methods = ['GET']27 28 def dispatch_request(self, name):31- return 'Hello %s!' % name29+ return f"Hello {name}!"30 31 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))32 33 When you want to decorate a pluggable view you will have to either do that77 unmodified lines111 defines.112 """113 114 def __init__(cls, name, bases, d):117- super(MethodViewType, cls).__init__(name, bases, d)115+ super().__init__(name, bases, d)116 117 if "methods" not in d:118 methods = set()119 12 unmodified lines132 if methods:133 cls.methods = methods134 135 138-class MethodView(with_metaclass(MethodViewType, View)):136+class MethodView(View, metaclass=MethodViewType):137 """A class-based view that dispatches request methods to the corresponding138 class methods. For example, if you implement a ``get`` method, it will be139 used to handle ``GET`` requests. ::140 15 unmodified lines156 # retry with GET.157 if meth is None and request.method == "HEAD":158 meth = getattr(self, "get", None)159 162- assert meth is not None, "Unimplemented method %r" % request.method160+ assert meth is not None, f"Unimplemented method {request.method!r}"161 return meth(*args, **kwargs)modified:src/flask/wrappers.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask.wrappers3 ~~~~~~~~~~~~~~4 15 unmodified lines20 json_module = json21 22 def on_json_loading_failed(self, e):23 if current_app and current_app.debug:25- raise BadRequest("Failed to decode JSON object: {0}".format(e))24+ raise BadRequest(f"Failed to decode JSON object: {e}")25 26 raise BadRequest()27 28 103 unmodified lines132 if current_app:133 return current_app.config["MAX_COOKIE_SIZE"]134 135 # return Werkzeug's default when not in an app context137- return super(Response, self).max_cookie_size136+ return super().max_cookie_sizemodified:tests/test_apps/cliapp/app.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 testapp = Flask("testapp")modified:tests/test_apps/cliapp/factory.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 4 def create_app():13 unmodified linesmodified:tests/test_apps/cliapp/importerrorapp.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 raise ImportError()4 1 unmodified linemodified:tests/test_apps/cliapp/multiapp.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 app1 = Flask("app1")4 app2 = Flask("app2")modified:tests/conftest.py+13 added-17 removed
1-# -*- coding: utf-8 -*-1 """2 tests.conftest3 ~~~~~~~~~~~~~~4 105 unmodified lines110 """111 if not request.param:112 return113 115- class LimitedLoader(object):114+ class LimitedLoader:115 def __init__(self, loader):116 self.loader = loader117 118 def __getattr__(self, name):120- if name in ("archive", "get_filename"):121- msg = "Mocking a loader which does not have `%s.`" % name122- raise AttributeError(msg)119+ if name in {"archive", "get_filename"}:120+ raise AttributeError(f"Mocking a loader which does not have {name!r}.")121 return getattr(self.loader, name)122 123 old_get_loader = pkgutil.get_loader124 21 unmodified lines146 def site_packages(modules_tmpdir, monkeypatch):147 """Create a fake site-packages."""148 rv = (149 modules_tmpdir.mkdir("lib")152- .mkdir("python{x[0]}.{x[1]}".format(x=sys.version_info))150+ .mkdir(f"python{sys.version_info.major}.{sys.version_info.minor}")151 .mkdir("site-packages")152 )153 monkeypatch.syspath_prepend(str(rv))154 return rv4 unmodified lines159 """Generate egg from package name inside base and put the egg into160 sys.path."""161 162 def inner(name, base=modules_tmpdir):165- if not isinstance(name, str):166- raise ValueError(name)163 base.join(name).ensure_dir()164 base.join(name).join("__init__.py").ensure()165 166 egg_setup = base.join("setup.py")167 egg_setup.write(168 textwrap.dedent(173- """174- from setuptools import setup175- setup(name='{0}',176- version='1.0',177- packages=['site_egg'],178- zip_safe=True)179- """.format(180- name169+ f"""170+ from setuptools import setup171+ setup(172+ name="{name}",173+ version="1.0",174+ packages=["site_egg"],175+ zip_safe=True,176 )177+ """178 )179 )180 181 import subprocess182 183 subprocess.check_call(184 [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)185 )190- egg_path, = modules_tmpdir.join("dist/").listdir()186+ (egg_path,) = modules_tmpdir.join("dist/").listdir()187 monkeypatch.syspath_prepend(str(egg_path))188 return egg_path189 190 return inner8 unmodified linesmodified:tests/test_appctx.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 tests.appctx3 ~~~~~~~~~~~~4 156 unmodified lines161 assert repr(flask.g) == "<flask.g of 'flask_test'>"162 163 164 def test_custom_app_ctx_globals_class(app):166- class CustomRequestGlobals(object):165+ class CustomRequestGlobals:166 def __init__(self):167 self.spam = "eggs"168 169 app.app_ctx_globals_class = CustomRequestGlobals18 unmodified lines188 with flask._request_ctx_stack.top:189 pass190 env = flask._request_ctx_stack.top.request.environ191 assert env["werkzeug.request"] is not None193- return u""192+ return ""193 194 res = client.get("/")195 assert res.status_code == 200196 assert res.data == b""23 unmodified linesmodified:tests/test_basic.py+31 added-42 removed
1-# -*- coding: utf-8 -*-1 """2 tests.basic3 ~~~~~~~~~~~~~~~~~~~~~4 17 unmodified lines22 from werkzeug.http import parse_date23 from werkzeug.routing import BuildError24 25 import flask27-from flask._compat import text_type26 27 28 def test_options_work(app, client):29 @app.route("/", methods=["GET", "POST"])59 unmodified lines89 rv = client.post("/")90 assert rv.status_code == 40591 assert sorted(rv.allow) == ["GET", "HEAD"]92 95- # Older versions of Werkzeug.test.Client don't have an options method96- if hasattr(client, "options"):97- rv = client.options("/")98- else:99- rv = client.open("/", method="OPTIONS")93+ rv = client.open("/", method="OPTIONS")100-94 assert rv.status_code == 40595 96 rv = client.head("/")97 assert rv.status_code == 2004 unmodified lines102 rv = client.delete("/more")103 assert rv.status_code == 405104 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]105 113- if hasattr(client, "options"):114- rv = client.options("/more")115- else:116- rv = client.open("/more", method="OPTIONS")106+ rv = client.open("/more", method="OPTIONS")117-107 assert rv.status_code == 405108 109 110 def test_request_dispatching(app, client):165 unmodified lines276 assert "httponly" in rv.headers["set-cookie"].lower()277 278 279 def test_session_using_application_root(app, client):291- class PrefixPathMiddleware(object):280+ class PrefixPathMiddleware:281 def __init__(self, app, prefix):282 self.app = app283 self.prefix = prefix284 75 unmodified lines360 361 rv = client.get("/", "http://localhost:5000/")362 assert "domain" not in rv.headers["set-cookie"].lower()363 w = recwarn.pop(UserWarning)375- assert '"localhost" is not a valid cookie domain' in str(w.message)364+ assert "'localhost' is not a valid cookie domain" in str(w.message)365 366 367 def test_session_ip_warning(recwarn, app, client):368 app.config.update(SERVER_NAME="127.0.0.1:5000")32 unmodified lines401 return ""402 403 @app.route("/test")404 def test():416- return text_type(flask.session.permanent)405+ return str(flask.session.permanent)406 407 rv = client.get("/")408 assert "set-cookie" in rv.headers409 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])171 unmodified lines581 # instead of propagating exceptions.582 583 @app.route("/")584 def index():596- flask.flash(u"Hello World")597- flask.flash(u"Hello World", "error")598- flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")585+ flask.flash("Hello World")586+ flask.flash("Hello World", "error")587+ flask.flash(flask.Markup("<em>Testing</em>"), "warning")588 return ""589 590 @app.route("/test/")591 def test():592 messages = flask.get_flashed_messages()593 assert list(messages) == [605- u"Hello World",606- u"Hello World",607- flask.Markup(u"<em>Testing</em>"),594+ "Hello World",595+ "Hello World",596+ flask.Markup("<em>Testing</em>"),597 ]598 return ""599 600 @app.route("/test_with_categories/")601 def test_with_categories():602 messages = flask.get_flashed_messages(with_categories=True)603 assert len(messages) == 3604 assert list(messages) == [616- ("message", u"Hello World"),617- ("error", u"Hello World"),618- ("warning", flask.Markup(u"<em>Testing</em>")),605+ ("message", "Hello World"),606+ ("error", "Hello World"),607+ ("warning", flask.Markup("<em>Testing</em>")),608 ]609 return ""610 611 @app.route("/test_filter/")612 def test_filter():613 messages = flask.get_flashed_messages(614 category_filter=["message"], with_categories=True615 )627- assert list(messages) == [("message", u"Hello World")]616+ assert list(messages) == [("message", "Hello World")]617 return ""618 619 @app.route("/test_filters/")620 def test_filters():621 messages = flask.get_flashed_messages(622 category_filter=["message", "warning"], with_categories=True623 )624 assert list(messages) == [636- ("message", u"Hello World"),637- ("warning", flask.Markup(u"<em>Testing</em>")),625+ ("message", "Hello World"),626+ ("warning", flask.Markup("<em>Testing</em>")),627 ]628 return ""629 630 @app.route("/test_filters_without_returning_categories/")631 def test_filters2():632 messages = flask.get_flashed_messages(category_filter=["message", "warning"])633 assert len(messages) == 2645- assert messages[0] == u"Hello World"646- assert messages[1] == flask.Markup(u"<em>Testing</em>")634+ assert messages[0] == "Hello World"635+ assert messages[1] == flask.Markup("<em>Testing</em>")636 return ""637 638 # Create new test client on each test to clean flashed messages.639 454 unmodified lines1094 with client:1095 with pytest.raises(DebugFilesKeyError) as e:1096 client.post("/fail", data={"foo": "index.txt"})1097 assert "no file contents were transmitted" in str(e.value)1109- assert 'This was submitted: "index.txt"' in str(e.value)1098+ assert "This was submitted: 'index.txt'" in str(e.value)1099 1100 1101 def test_response_types(app, client):1102 @app.route("/text")1103 def from_text():1115- return u"Hällo Wörld"1104+ return "Hällo Wörld"1105 1106 @app.route("/bytes")1107 def from_bytes():1119- return u"Hällo Wörld".encode("utf-8")1108+ return "Hällo Wörld".encode()1109 1110 @app.route("/full_tuple")1111 def from_full_tuple():1112 return (28 unmodified lines1141 @app.route("/dict")1142 def from_dict():1143 return {"foo": "bar"}, 2011144 1156- assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1157- assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")1145+ assert client.get("/text").data == "Hällo Wörld".encode()1146+ assert client.get("/bytes").data == "Hällo Wörld".encode()1147 1148 rv = client.get("/full_tuple")1149 assert rv.data == b"Meh"1150 assert rv.headers["X-Foo"] == "Testing"458 unmodified lines1609 assert url == expected1610 1611 1612 def test_nonascii_pathinfo(app, client):1624- @app.route(u"/киртест")1613+ @app.route("/киртест")1614 def index():1615 return "Hello World!"1616 1628- rv = client.get(u"/киртест")1617+ rv = client.get("/киртест")1618 assert rv.data == b"Hello World!"1619 1620 1621 def test_debug_mode_complains_after_first_request(app, client):198 unmodified lines1820 app.config["SERVER_NAME"] = "localhost.localdomain"1821 1822 @app.route("/", subdomain="<user>")1823 def index(user):1835- return "index for %s" % user1824+ return f"index for {user}"1825 1826 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1827 assert rv.data == b"index for mitsuhiko"1828 4 unmodified lines1833 client = app.test_client()1834 1835 @app.route("/", subdomain="<user>")1836 def index(user):1848- return "index for %s" % user1837+ return f"index for {user}"1838 1839 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1840 assert rv.data == b"index for mitsuhiko"1841 31 unmodified lines1873 assert rv.data == b"b"1874 1875 1876 def test_multi_route_class_views(app, client):1888- class View(object):1877+ class View:1878 def __init__(self, app):1879 app.add_url_rule("/", "index", self.index)1880 app.add_url_rule("/<test>/", "index", self.index)1881 23 unmodified lines1905 rv = {}1906 1907 # Mocks werkzeug.serving.run_simple method1908 def run_simple_mock(hostname, port, application, *args, **kwargs):1920- rv["result"] = "running on %s:%s ..." % (hostname, port)1909+ rv["result"] = f"running on {hostname}:{port} ..."1910 1911 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1912 hostname, port = "localhost", 80001913 app.run(hostname, port, debug=True)1925- assert rv["result"] == "running on %s:%s ..." % (hostname, port)1914+ assert rv["result"] == f"running on {hostname}:{port} ..."1915 1916 1917 @pytest.mark.parametrize(1918 "host,port,server_name,expect_host,expect_port",50 unmodified linesmodified:tests/test_blueprints.py+2 added-4 removed
1-# -*- coding: utf-8 -*-1 """2 tests.blueprints3 ~~~~~~~~~~~~~~~~4 8 unmodified lines13 from jinja2 import TemplateNotFound14 from werkzeug.http import parse_cache_control_header15 16 import flask18-from flask._compat import text_type17 18 19 def test_blueprint_specific_error_handling(app, client):20 frontend = flask.Blueprint("frontend", __name__)122 unmodified lines143 bp = flask.Blueprint("test", __name__)144 145 @bp.route("/foo", defaults={"baz": 42})146 def foo(bar, baz):149- return "%s/%d" % (bar, baz)147+ return f"{bar}/{baz:d}"148 149 @bp.route("/bar")150 def bar(bar):153- return text_type(bar)151+ return str(bar)152 153 app.register_blueprint(bp, url_prefix="/1", url_defaults={"bar": 23})154 app.register_blueprint(bp, url_prefix="/2", url_defaults={"bar": 19})155 706 unmodified linesmodified:tests/test_cli.py+10 added-18 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_cli3 ~~~~~~~~~~~~~~4 1 unmodified line6 :license: BSD-3-Clause7 """8 # This file was part of Flask-CLI and was modified under the terms of9 # its Revised BSD License. Copyright © 2015 CERN.11-from __future__ import absolute_import12-10 import os11 import ssl12 import sys13 import types243 unmodified lines257 from flask import __version__ as flask_version258 from werkzeug import __version__ as werkzeug_version259 from platform import python_version260 264- class MockCtx(object):261+ class MockCtx:262 resilient_parsing = False263 color = None264 265 def exit(self):1 unmodified line267 268 ctx = MockCtx()269 get_version(ctx, None, "test")270 out, err = capsys.readouterr()274- assert "Python " + python_version() in out275- assert "Flask " + flask_version in out276- assert "Werkzeug " + werkzeug_version in out271+ assert f"Python {python_version()}" in out272+ assert f"Flask {flask_version}" in out273+ assert f"Werkzeug {werkzeug_version}" in out274 275 276 def test_scriptinfo(test_apps, monkeypatch):277 """Test of ScriptInfo."""9 unmodified lines287 obj = ScriptInfo(app_import_path=cli_app_path)288 app = obj.load_app()289 assert app.name == "testapp"290 assert obj.load_app() is app294- obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")291+ obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")292 app = obj.load_app()293 assert app.name == "testapp"294 assert obj.load_app() is app295 109 unmodified lines405 click.echo(str(current_app.debug))406 407 result = runner.invoke(cli, ["test"])408 assert result.exit_code == 0412- assert result.output == "%s\n" % str(not set_debug_flag)409+ assert result.output == f"{not set_debug_flag}\n"410 411 412 def test_print_exceptions(runner):413 """Print the stacktrace if the CLI."""171 unmodified lines585 # ImportError586 with pytest.raises(click.BadParameter):587 run_command.make_context("run", ["--cert", "not_here"])588 592- # not an SSLContext593- if sys.version_info >= (2, 7, 9):594- with pytest.raises(click.BadParameter):595- run_command.make_context("run", ["--cert", "flask"])589+ with pytest.raises(click.BadParameter):590+ run_command.make_context("run", ["--cert", "flask"])591 592 # SSLContext598- if sys.version_info < (2, 7, 9):599- ssl_context = object()600- else:601- ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)593+ ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)594 595 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)596 ctx = run_command.make_context("run", ["--cert", "ssl_context"])597 assert ctx.params["cert"] is ssl_context57 unmodified lines655 bp = Blueprint("blue", __name__, cli_group="blue")656 app.register_blueprint(bp)657 658 result = app.test_cli_runner().invoke(args=["blue", "--help"])667- assert result.exit_code == 2, "Unexpected success:\n\n" + result.output659+ assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"modified:tests/test_config.py+8 added-14 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_config3 ~~~~~~~~~~~~~~~~~4 7 unmodified lines12 13 import pytest14 15 import flask17-from flask._compat import PY216 17 18 # config keys used for the TestConfig19 TEST_KEY = "foo"7 unmodified lines27 28 29 def test_config_from_pyfile():30 app = flask.Flask(__name__)33- app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")31+ app.config.from_pyfile(f"{__file__.rsplit('.', 1)[0]}.py")32 common_object_test(app)33 34 35 def test_config_from_object():27 unmodified lines63 app.config.from_mapping({}, {})64 65 66 def test_config_from_class():69- class Base(object):67+ class Base:68 TEST_KEY = "foo"69 70 class Test(Base):71 SECRET_KEY = "config"11 unmodified lines83 assert "'FOO_SETTINGS' is not set" in str(e.value)84 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)85 86 monkeypatch.setattr(89- "os.environ", {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}87+ "os.environ", {"FOO_SETTINGS": f"{__file__.rsplit('.', 1)[0]}.py"}88 )89 assert app.config.from_envvar("FOO_SETTINGS")90 common_object_test(app)91 92 unmodified lines184 def test_from_pyfile_weird_encoding(tmpdir, encoding):185 f = tmpdir.join("my_config.py")186 f.write_binary(187 textwrap.dedent(190- u"""191- # -*- coding: {0} -*-192- TEST_VALUE = "föö"193- """.format(194- encoding195- )188+ f"""189+ # -*- coding: {encoding} -*-190+ TEST_VALUE = "föö"191+ """192 ).encode(encoding)193 )194 app = flask.Flask(__name__)195 app.config.from_pyfile(str(f))196 value = app.config["TEST_VALUE"]201- if PY2:202- value = value.decode(encoding)203- assert value == u"föö"197+ assert value == "föö"modified:tests/test_converters.py+1 added-1 removed
8 unmodified lines9 def to_python(self, value):10 return value.split(",")11 12 def to_url(self, value):13- base_to_url = super(ListConverter, self).to_url13+ base_to_url = super().to_url14 return ",".join(base_to_url(x) for x in value)15 16 app.url_map.converters["list"] = ListConverter17 23 unmodified linesdeleted:tests/test_deprecations.py-12 removed
1-import pytest2-3-from flask import json_available4-5-6-def test_json_available():7- with pytest.deprecated_call() as rec:8- assert json_available9- assert json_available == True # noqa E71210- assert json_available != False # noqa E71211-12- assert len(rec.list) == 3modified:tests/test_helpers.py+36 added-48 removed
1-# -*- coding: utf-8 -*-1 """2 tests.helpers3 ~~~~~~~~~~~~~~~~~~~~~~~4 17 unmodified lines22 from werkzeug.http import parse_options_header23 24 import flask25 from flask import json27-from flask._compat import PY228-from flask._compat import StringIO29-from flask._compat import text_type26 from flask.helpers import get_debug_flag27 from flask.helpers import get_env28 29 6 unmodified lines36 except LookupError:37 return False38 39 44-class FakePath(object):40+class FakePath:41 """Fake object to represent a ``PathLike object``.42 43 This represents a ``pathlib.Path`` object in python 3.44 See: https://www.python.org/dev/peps/pep-0519/26 unmodified lines71 def dst(self, dt):72 return datetime.timedelta()73 74 79-class TestJSON(object):75+class TestJSON:76 @pytest.mark.parametrize(81- "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": u"🐍"})77+ "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": "🐍"})78 )79 @pytest.mark.parametrize(80 "encoding",81 (8 unmodified lines90 ),91 )92 def test_detect_encoding(self, value, encoding):93 data = json.dumps(value).encode(encoding)98- assert json.detect_encoding(data) == encoding94 assert json.loads(data) == value95 96 @pytest.mark.parametrize("debug", (True, False))97 def test_bad_request_debug_message(self, app, client, debug):12 unmodified lines110 111 def test_json_bad_requests(self, app, client):112 @app.route("/json", methods=["POST"])113 def return_json():119- return flask.jsonify(foo=text_type(flask.request.get_json()))114+ return flask.jsonify(foo=str(flask.request.get_json()))115 116 rv = client.post("/json", data="malformed", content_type="application/json")117 assert rv.status_code == 400118 5 unmodified lines124 rv = client.post("/json", data='"foo"', content_type="application/x+json")125 assert rv.data == b"foo"126 127 @pytest.mark.parametrize(133- "test_value,expected", [(True, '"\\u2603"'), (False, u'"\u2603"')]128+ "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')]129 )130 def test_json_as_unicode(self, test_value, expected, app, app_ctx):131 132 app.config["JSON_AS_ASCII"] = test_value138- rv = flask.json.dumps(u"\N{SNOWMAN}")133+ rv = flask.json.dumps("\N{SNOWMAN}")134 assert rv == expected135 136 def test_json_dump_to_file(self, app, app_ctx):137 test_data = {"name": "Flask"}143- out = StringIO()138+ out = io.StringIO()139 140 flask.json.dump(test_data, out)141 out.seek(0)142 rv = flask.json.load(out)72 unmodified lines215 datetime.date(1975, 1, 5),216 )217 218 for i, d in enumerate(test_dates):224- url = "/datetest{0}".format(i)219+ url = f"/datetest{i}"220 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))221 rv = client.get(url)222 assert rv.mimetype == "application/json"223 assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple())24 unmodified lines248 def test_json_attr(self, app, client):249 @app.route("/add", methods=["POST"])250 def add():251 json = flask.request.get_json()257- return text_type(json["a"] + json["b"])252+ return str(json["a"] + json["b"])253 254 rv = client.post(255 "/add",256 data=flask.json.dumps({"a": 1, "b": 2}),3 unmodified lines260 261 def test_template_escaping(self, app, req_ctx):262 render = flask.render_template_string263 rv = flask.json.htmlsafe_dumps("</script>")269- assert rv == u'"\\u003c/script\\u003e"'270- assert type(rv) == text_type264+ assert rv == '"\\u003c/script\\u003e"'265+ assert type(rv) is str266 rv = render('{{ "</script>"|tojson }}')267 assert rv == '"\\u003c/script\\u003e"'268 rv = render('{{ "<\0/script>"|tojson }}')269 assert rv == '"\\u003c\\u0000/script\\u003e"'8 unmodified lines278 )279 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'280 281 def test_json_customization(self, app, client):287- class X(object): # noqa: B903, for Python2 compatibility282+ class X: # noqa: B903, for Python2 compatibility283 def __init__(self, val):284 self.val = val285 286 class MyEncoder(flask.json.JSONEncoder):287 def default(self, o):288 if isinstance(o, X):294- return "<%d>" % o.val289+ return f"<{o.val}>"290 return flask.json.JSONEncoder.default(self, o)291 292 class MyDecoder(flask.json.JSONDecoder):293 def __init__(self, *args, **kwargs):19 unmodified lines313 )314 assert rv.data == b'"<42>"'315 316 def test_blueprint_json_customization(self, app, client):322- class X(object): # noqa: B903, for Python2 compatibility317+ class X:318+ __slots__ = ("val",)319+320 def __init__(self, val):321 self.val = val322 323 class MyEncoder(flask.json.JSONEncoder):324 def default(self, o):325 if isinstance(o, X):329- return "<%d>" % o.val326+ return f"<{o.val}>"327 328 return flask.json.JSONEncoder.default(self, o)329 330 class MyDecoder(flask.json.JSONDecoder):37 unmodified lines368 @app.route("/")369 def index():370 return flask.request.args["foo"]371 375- rv = client.get(u"/?foo=정상처리".encode("euc-kr"))372+ rv = client.get("/?foo=정상처리".encode("euc-kr"))373 assert rv.status_code == 200377- assert rv.data == u"정상처리".encode("utf-8")374+ assert rv.data == "정상처리".encode()375 376 def test_json_key_sorting(self, app, client):377 app.debug = True378 64 unmodified lines443 except AssertionError:444 assert lines == sorted_by_str445 446 450-class PyStringIO(object):447+class PyBytesIO:448 def __init__(self, *args, **kwargs):449 self._io = io.BytesIO(*args, **kwargs)450 451 def __getattr__(self, name):452 return getattr(self._io, name)453 454 458-class TestSendfile(object):455+class TestSendfile:456 def test_send_file_regular(self, app, req_ctx):457 rv = flask.send_file("static/index.html")458 assert rv.direct_passthrough459 assert rv.mimetype == "text/html"39 unmodified lines499 "opener",500 [501 lambda app: open(os.path.join(app.static_folder, "index.html"), "rb"),502 lambda app: io.BytesIO(b"Test"),506- pytest.param(507- lambda app: StringIO("Test"),508- marks=pytest.mark.skipif(not PY2, reason="Python 2 only"),509- ),510- lambda app: PyStringIO(b"Test"),503+ lambda app: PyBytesIO(b"Test"),504 ],505 )506 @pytest.mark.usefixtures("req_ctx")507 def test_send_file_object(self, app, opener):8 unmodified lines516 517 @pytest.mark.parametrize(518 "opener",519 [527- lambda app: io.StringIO(u"Test"),528- pytest.param(529- lambda app: open(os.path.join(app.static_folder, "index.html")),530- marks=pytest.mark.skipif(PY2, reason="Python 3 only"),531- ),520+ lambda app: io.StringIO("Test"),521+ lambda app: open(os.path.join(app.static_folder, "index.html")),522 ],523 )524 @pytest.mark.usefixtures("req_ctx")525 def test_send_file_text_fails(self, app, opener):147 unmodified lines673 ("filename", "ascii", "utf8"),674 (675 ("index.html", "index.html", False),676 (687- u"Ñandú/pingüino.txt",677+ "Ñandú/pingüino.txt",678 '"Nandu/pinguino.txt"',679 "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",680 ),691- (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),692- # Native string not marked as Unicode on Python 2693- ("tést.txt", "test.txt", "t%C3%A9st.txt"),681+ ("Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),682 # ":/" are not safe in filename* value695- (u"те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"),683+ ("те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"),684 ),685 )686 def test_attachment_filename_encoding(self, filename, ascii, utf8):687 rv = flask.send_file(688 "static/index.html", as_attachment=True, attachment_filename=filename689 )690 rv.close()691 content_disposition = rv.headers["Content-Disposition"]704- assert "filename=%s" % ascii in content_disposition692+ assert f"filename={ascii}" in content_disposition693 if utf8:706- assert "filename*=UTF-8''" + utf8 in content_disposition694+ assert f"filename*=UTF-8''{utf8}" in content_disposition695 else:696 assert "filename*=UTF-8''" not in content_disposition697 698 def test_static_file(self, app, req_ctx):76 unmodified lines775 with pytest.raises(exception):776 flask.send_from_directory("static", "bad\x00")777 778 791-class TestUrlFor(object):779+class TestUrlFor:780 def test_url_for_with_anchor(self, app, req_ctx):781 @app.route("/")782 def index():783 return "42"35 unmodified lines819 class MyView(MethodView):820 def get(self, id=None):821 if id is None:822 return "List"835- return "Get %d" % id823+ return f"Get {id:d}"824 825 def post(self):826 return "Create"827 6 unmodified lines834 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"835 assert flask.url_for("myview", _method="POST") == "/myview/create"836 837 850-class TestNoImports(object):838+class TestNoImports:839 """Test Flasks are created without import.840 841 Avoiding ``__import__`` helps create Flask instances where there are errors842 at import time. Those runtime errors will be apparent to the user soon10 unmodified lines853 except NotImplementedError:854 AssertionError("Flask(import_name) is importing import_name.")855 856 869-class TestStreaming(object):857+class TestStreaming:858 def test_streaming_with_context(self, app, client):859 @app.route("/")860 def index():861 def generate():22 unmodified lines884 885 def test_streaming_with_context_and_custom_close(self, app, client):886 called = []887 900- class Wrapper(object):888+ class Wrapper:889 def __init__(self, gen):890 self._gen = gen891 892 def __iter__(self):34 unmodified lines927 rv = client.get("/")928 assert rv.data == b"flask"929 930 943-class TestSafeJoin(object):931+class TestSafeJoin:932 def test_safe_join(self):933 # Valid combinations of *args and expected joined paths.934 passing = (935 (("a/b/c",), "a/b/c"),32 unmodified lines968 with pytest.raises(NotFound):969 print(flask.safe_join(*args))970 971 984-class TestHelpers(object):972+class TestHelpers:973 @pytest.mark.parametrize(974 "debug, expected_flag, expected_default_flag",975 [976 ("", False, False),55 unmodified linesmodified:tests/test_instance_config.py+3 added-19 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_instance3 ~~~~~~~~~~~~~~~~~~~4 5 unmodified lines10 11 import pytest12 13 import flask15-from flask._compat import PY214 15 16 def test_explicit_instance_paths(modules_tmpdir):17 with pytest.raises(ValueError) as excinfo:3 unmodified lines21 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))22 assert app.instance_path == str(modules_tmpdir)23 24 27-@pytest.mark.xfail(reason="TODO: weird interaction with tox")25+@pytest.mark.xfail(reason="weird interaction with tox")26 def test_main_module_paths(modules_tmpdir, purge_module):27 app = modules_tmpdir.join("main_app.py")28 app.write('import flask\n\napp = flask.Flask("__main__")')29 purge_module("main_app")3 unmodified lines33 here = os.path.abspath(os.getcwd())34 assert app.instance_path == os.path.join(here, "instance")35 36 37+@pytest.mark.xfail(reason="weird interaction with tox")38 def test_uninstalled_module_paths(modules_tmpdir, purge_module):39 app = modules_tmpdir.join("config_module_app.py").write(40 "import os\n"41 "import flask\n"6 unmodified lines48 49 assert app.instance_path == str(modules_tmpdir.join("instance"))50 51 52+@pytest.mark.xfail(reason="weird interaction with tox")53 def test_uninstalled_package_paths(modules_tmpdir, purge_module):54 app = modules_tmpdir.mkdir("config_package_app")55 init = app.join("__init__.py")56 init.write(68 unmodified lines125 )126 finally:127 if "site_egg" in sys.modules:128 del sys.modules["site_egg"]129-130-131-@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")132-def test_meta_path_loader_without_is_package(request, modules_tmpdir):133- app = modules_tmpdir.join("unimportable.py")134- app.write("import flask\napp = flask.Flask(__name__)")135-136- class Loader(object):137- def find_module(self, name, path=None):138- return self139-140- sys.meta_path.append(Loader())141- request.addfinalizer(sys.meta_path.pop)142-143- with pytest.raises(AttributeError):144- import unimportable # noqa: F401modified:tests/test_json_tag.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_json_tag3 ~~~~~~~~~~~~~~~~~~~4 41 unmodified lines46 assert isinstance(s.order[0], TagDict)47 48 49 def test_custom_tag():51- class Foo(object): # noqa: B903, for Python2 compatibility50+ class Foo: # noqa: B903, for Python2 compatibility51 def __init__(self, data):52 self.data = data53 54 class TagFoo(JSONTag):38 unmodified linesmodified:tests/test_logging.py+1 added-11 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_logging3 ~~~~~~~~~~~~~~~~~~~4 1 unmodified line6 :license: BSD-3-Clause7 """8 import logging9 import sys10+from io import StringIO11 12 import pytest13 14-from flask._compat import StringIO14 from flask.logging import default_handler15 from flask.logging import has_level_handler16 from flask.logging import wsgi_errors_stream17 84 unmodified lines102 assert rv.data103 err = stream.getvalue()104 assert "Exception on / [GET]" in err105 assert "Exception: test" in err107-108-109-def test_warn_old_config(app, request):110- old_logger = logging.getLogger("flask.app")111- old_logger.setLevel(logging.DEBUG)112- request.addfinalizer(lambda: old_logger.setLevel(logging.NOTSET))113-114- with pytest.warns(UserWarning):115- assert app.logger.getEffectiveLevel() == logging.WARNINGdeleted:tests/test_meta.py-6 removed
1-import io2-3-4-def test_changelog_utf8_compatible():5- with io.open("CHANGES.rst", encoding="UTF-8") as f:6- f.read()modified:tests/test_regression.py+6 added-8 removed
1-# -*- coding: utf-8 -*-1 """2 tests.regression3 ~~~~~~~~~~~~~~~~~~~~~~~~~~4 2 unmodified lines7 :copyright: 2010 Pallets8 :license: BSD-3-Clause9 """10 import gc12-import sys11+import platform12 import threading13 14 import pytest15 from werkzeug.exceptions import NotFound2 unmodified lines18 19 _gc_lock = threading.Lock()20 21 23-class assert_no_leak(object):22+class assert_no_leak:23 def __enter__(self):24 gc.disable()25 _gc_lock.acquire()26 loc = flask._request_ctx_stack._local15 unmodified lines42 _gc_lock.release()43 gc.enable()44 45 46+@pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="CPython only")47 def test_memory_consumption():48 app = flask.Flask(__name__)49 50 @app.route("/")8 unmodified lines59 60 # Trigger caches61 fire()62 63- # This test only works on CPython 2.7.64- if sys.version_info >= (2, 7) and not hasattr(sys, "pypy_translation_info"):65- with assert_no_leak():66- for _x in range(10):67- fire()63+ with assert_no_leak():64+ for _x in range(10):65+ fire()66 67 68 def test_safe_join_toplevel_pardir():69 from flask.helpers import safe_join26 unmodified linesmodified:tests/test_reqctx.py+6 added-15 removed
1-# -*- coding: utf-8 -*-1 """2 tests.reqctx3 ~~~~~~~~~~~~4 104 unmodified lines109 110 def test_context_binding(app):111 @app.route("/")112 def index():114- return "Hello %s!" % flask.request.args["name"]113+ return f"Hello {flask.request.args['name']}!"114 115 @app.route("/meh")116 def meh():117 return flask.request.url19 unmodified lines137 138 def test_manual_context_binding(app):139 @app.route("/")140 def index():142- return "Hello %s!" % flask.request.args["name"]141+ return f"Hello {flask.request.args['name']}!"142 143 ctx = app.test_request_context("/?name=World")144 ctx.push()145 assert index() == "Hello World!"2 unmodified lines148 index()149 150 151 @pytest.mark.skipif(greenlet is None, reason="greenlet not installed")153-class TestGreenletContextCopying(object):152+class TestGreenletContextCopying:153 def test_greenlet_context_copying(self, app, client):154 greenlets = []155 156 @app.route("/")80 unmodified lines237 def get_cookie_name(self, app):238 if flask.request.url.endswith("dynamic_cookie"):239 return "dynamic_cookie_name"240 else:242- return super(PathAwareSessionInterface, self).get_cookie_name(app)241+ return super().get_cookie_name(app)242 243 class CustomFlask(flask.Flask):244 session_interface = PathAwareSessionInterface()245 37 unmodified lines283 284 def test_bad_environ_raises_bad_request():285 app = flask.Flask(__name__)286 288- # We cannot use app.test_client() for the Unicode-rich Host header,289- # because werkzeug enforces latin1 on Python 2.290- # However it works when actually passed to the server.291-287 from flask.testing import EnvironBuilder288 289 builder = EnvironBuilder(app)290 environ = builder.get_environ()291 292 # use a non-printable character in the Host - this is key to this test298- environ["HTTP_HOST"] = u"\x8a"293+ environ["HTTP_HOST"] = "\x8a"294 295 with app.request_context(environ):296 response = app.full_dispatch_request()297 assert response.status_code == 4005 unmodified lines303 @app.route("/")304 def index():305 return "Hello World!"306 312- # We cannot use app.test_client() for the Unicode-rich Host header,313- # because werkzeug enforces latin1 on Python 2.314- # However it works when actually passed to the server.315-307 from flask.testing import EnvironBuilder308 309 builder = EnvironBuilder(app)310 environ = builder.get_environ()311 312 # these characters are all IDNA-compatible322- environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"313+ environ["HTTP_HOST"] = "ąśźäüжŠßя.com"314 315 with app.request_context(environ):316 response = app.full_dispatch_request()317 12 unmodified linesmodified:tests/test_signals.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.signals3 ~~~~~~~~~~~~~~~~~~~~~~~4 201 unmodified linesmodified:tests/test_subclassing.py+2 added-2 removed
1-# -*- coding: utf-8 -*-1 """2 tests.subclassing3 ~~~~~~~~~~~~~~~~~4 2 unmodified lines7 8 :copyright: 2010 Pallets9 :license: BSD-3-Clause10 """11+from io import StringIO12+13 import flask13-from flask._compat import StringIO14 15 16 def test_suppressed_exception_logging():17 class SuppressedFlask(flask.Flask):14 unmodified linesmodified:tests/test_templating.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 tests.templating3 ~~~~~~~~~~~~~~~~4 408 unmodified lines413 class _TestHandler(logging.Handler):414 def handle(self, record):415 called.append(True)416 text = str(record.msg)418- assert '1: trying loader of application "blueprintapp"' in text417+ assert "1: trying loader of application 'blueprintapp'" in text418 assert (420- '2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"419+ "2: trying loader of blueprint 'admin' (blueprintapp.apps.admin)"420 ) in text421 assert (423- 'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"422+ "trying loader of blueprint 'frontend' (blueprintapp.apps.frontend)"423 ) in text424 assert "Error: the template could not be found" in text425 assert (427- "looked up from an endpoint that belongs to " 'the blueprint "frontend"'426+ "looked up from an endpoint that belongs to the blueprint 'frontend'"427 ) in text428 assert "See https://flask.palletsprojects.com/blueprints/#templates" in text429 430 with app.test_client() as c:22 unmodified linesmodified:tests/test_testing.py+9 added-23 removed
1-# -*- coding: utf-8 -*-1 """2 tests.testing3 ~~~~~~~~~~~~~4 7 unmodified lines12 import werkzeug13 14 import flask15 from flask import appcontext_popped17-from flask._compat import text_type16 from flask.cli import ScriptInfo17 from flask.json import jsonify18 from flask.testing import EnvironBuilder19 from flask.testing import FlaskCliRunner22-from flask.testing import make_test_environ_builder20 21 try:22 import blinker23 except ImportError:34 unmodified lines58 return flask.request.remote_addr59 60 rv = client.get("/")61 assert rv.data == b"127.0.0.1"65- assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__62+ assert flask.g.user_agent == f"werkzeug/{werkzeug.__version__}"63 64 65 def test_environ_base_modified(app, client, app_ctx):66 @app.route("/")50 unmodified lines117 assert eb.script_root == ""118 assert eb.path == "/"119 120 124-def test_make_test_environ_builder(app):125- with pytest.deprecated_call():126- eb = make_test_environ_builder(app, "https://example.com/")127- assert eb.url_scheme == "https"128- assert eb.host == "example.com"129- assert eb.script_root == ""130- assert eb.path == "/"131-132-121 def test_environbuilder_json_dumps(app):122 """EnvironBuilder.json_dumps() takes settings from the app."""123 app.config["JSON_AS_ASCII"] = False136- eb = EnvironBuilder(app, json=u"\u20ac")137- assert eb.input_stream.read().decode("utf8") == u'"\u20ac"'124+ eb = EnvironBuilder(app, json="\u20ac")125+ assert eb.input_stream.read().decode("utf8") == '"\u20ac"'126 127 128 def test_blueprint_with_subdomain():129 app = flask.Flask(__name__, subdomain_matching=True)37 unmodified lines167 168 rv = client.get("/")169 assert rv.data == b"index"170 assert flask.session.get("data") == "foo"171+172 rv = client.post("/", data={}, follow_redirects=True)173 assert rv.data == b"foo"174+ assert flask.session.get("data") == "foo"175 186- # This support requires a new Werkzeug version187- if not hasattr(client, "redirect_client"):188- assert flask.session.get("data") == "foo"189-176 rv = client.get("/getsession")177 assert rv.data == b"foo"178 179 180 def test_session_transactions(app, client):181 @app.route("/")182 def index():197- return text_type(flask.session["foo"])183+ return str(flask.session["foo"])184 185 with client:186 with client.session_transaction() as sess:187 assert len(sess) == 0132 unmodified lines320 @pytest.mark.skipif(blinker is None, reason="blinker is not installed")321 def test_client_json_no_app_context(app, client):322 @app.route("/hello", methods=["POST"])323 def hello():338- return "Hello, {}!".format(flask.request.json["name"])324+ return f"Hello, {flask.request.json['name']}!"325 340- class Namespace(object):326+ class Namespace:327 count = 0328 329 def add(self, app):330 self.count += 169 unmodified lines400 assert "Hello" in result.output401 402 403 def test_cli_custom_obj(app):418- class NS(object):404+ class NS:405 called = False406 407 def create_app():408 NS.called = True25 unmodified linesmodified:tests/test_user_error_handler.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_user_error_handler3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~4 23 unmodified lines28 assert isinstance(e, InternalServerError)29 original = getattr(e, "original_exception", None)30 31 if original is not None:33- return "wrapped " + type(original).__name__32+ return f"wrapped {type(original).__name__}"33 34 return "direct"35 36 @app.route("/custom")169 unmodified lines206 # Don't handle RequestRedirect raised when adding slash.207 assert c.get("/slash", follow_redirects=True).data == b"slash"208 209 211-class TestGenericHandlers(object):210+class TestGenericHandlers:211 """Test how very generic handlers are dispatched to."""212 213 class Custom(Exception):214 pass22 unmodified lines237 def report_error(self, e):238 original = getattr(e, "original_exception", None)239 240 if original is not None:242- return "wrapped " + type(original).__name__241+ return f"wrapped {type(original).__name__}"242 244- return "direct " + type(e).__name__243+ return f"direct {type(e).__name__}"244 245 @pytest.mark.parametrize("to_handle", (InternalServerError, 500))246 def test_handle_class_or_code(self, app, client, to_handle):247 """``InternalServerError`` and ``500`` are aliases, they should41 unmodified linesmodified:tests/test_views.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.views3 ~~~~~~~~~~~4 247 unmodified linesmodified:.azure-pipelines.yml+36 added-77 removed
1 trigger:2- - 'master'2+ - master3 - '*.x'4 5-jobs:6- - job: Tests7- variables:8- vmImage: 'ubuntu-latest'9- python.version: '3.8'10- TOXENV: 'py,coverage-ci'5+variables:6+ vmImage: ubuntu-latest7+ python.version: '3.8'8+ TOXENV: py11- hasTestResults: 'true'9 13- strategy:14- matrix:15- Python 3.8 Linux:16- vmImage: 'ubuntu-latest'17- Python 3.8 Windows:18- vmImage: 'windows-latest'19- Python 3.8 Mac:20- vmImage: 'macos-latest'21- PyPy 3 Linux:22- python.version: 'pypy3'23- Python 3.7 Linux:24- python.version: '3.7'25- Python 3.6 Linux:26- python.version: '3.6'27- Python 3.5 Linux:28- python.version: '3.5'29- Python 2.7 Linux:30- python.version: '2.7'31- Python 2.7 Windows:32- python.version: '2.7'33- vmImage: 'windows-latest'34- Docs:35- TOXENV: 'docs'36- hasTestResults: 'false'37- Style:38- TOXENV: 'style'39- hasTestResults: 'false'40- VersionRange:41- TOXENV: 'devel,lowest,coverage-ci'10+strategy:11+ matrix:12+ Linux:13+ vmImage: ubuntu-latest14+ Windows:15+ vmImage: windows-latest16+ Mac:17+ vmImage: macos-latest18+ Python 3.7:19+ python.version: '3.7'20+ Python 3.6:21+ python.version: '3.6'22+ PyPy 3:23+ python.version: pypy324+ Version Range:25+ TOXENV: 'devel,lowest'26+ Docs:27+ TOXENV: docs28+ Style:29+ TOXENV: style30 43- pool:44- vmImage: $[ variables.vmImage ]31+pool:32+ vmImage: $[ variables.vmImage ]33 46- steps:47- - task: UsePythonVersion@048- inputs:49- versionSpec: $(python.version)50- displayName: Use Python $(python.version)34+steps:35+ - task: UsePythonVersion@036+ inputs:37+ versionSpec: $(python.version)38+ displayName: Use Python $(python.version)39 52- - script: pip --disable-pip-version-check install -U tox53- displayName: Install tox40+ - script: pip --disable-pip-version-check install -U tox41+ displayName: Install tox42 55- - script: tox -s false -- --junitxml=test-results.xml tests examples56- displayName: Run tox57-58- - task: PublishTestResults@259- inputs:60- testResultsFiles: test-results.xml61- testRunTitle: $(Agent.JobName)62- condition: eq(variables['hasTestResults'], 'true')63- displayName: Publish test results64-65- - task: PublishCodeCoverageResults@166- inputs:67- codeCoverageTool: Cobertura68- summaryFileLocation: coverage.xml69- condition: eq(variables['hasTestResults'], 'true')70- displayName: Publish coverage results71-72- # Test on the nightly version of Python.73- # Use a container since Azure Pipelines may not have the latest build.74- - job: FlaskOnNightly75- pool:76- vmImage: ubuntu-latest77- container: python:rc-stretch78- steps:79- - script: |80- echo "##vso[task.prependPath]$HOME/.local/bin"81- pip --disable-pip-version-check install --user -U tox82- displayName: Install tox83-84- - script: tox -e nightly85- displayName: Run tox43+ - script: tox44+ displayName: Run toxmodified:.pre-commit-config.yaml+13 added-6 removed
1 repos:2+ - repo: https://github.com/asottile/pyupgrade3+ rev: v2.1.04+ hooks:5+ - id: pyupgrade6+ args: ["--py36-plus"]7 - repo: https://github.com/asottile/reorder_python_imports3- rev: v1.5.08+ rev: v2.1.09 hooks:10 - id: reorder-python-imports11 name: Reorder Python imports (src, tests)12 files: "^(?!examples/)"8- args: ["--application-directories", ".:src"]13+ args: ["--application-directories", "src"]14 - repo: https://github.com/python/black10- rev: 19.3b015+ rev: 19.10b016 hooks:17 - id: black18 - repo: https://gitlab.com/pycqa/flake814- rev: 3.7.719+ rev: 3.7.920 hooks:21 - id: flake817- additional_dependencies: [flake8-bugbear]22+ additional_dependencies:23+ - flake8-bugbear24+ - flake8-implicit-str-concat25 - repo: https://github.com/pre-commit/pre-commit-hooks19- rev: v2.2.326+ rev: v2.5.027 hooks:28 - id: check-byte-order-marker29 - id: trailing-whitespace30 - id: end-of-file-fixermodified:CHANGES.rst+8 added-10 removed
1 .. currentmodule:: flask2 3-Version 1.2.03+Version 2.0.04 -------------5 6 Unreleased7 8+- Drop support for Python 2 and 3.5.9 - Add :meth:`sessions.SessionInterface.get_cookie_name` to allow10 setting the session cookie name dynamically. :pr:`3369`11 - Add :meth:`Config.from_file` to load config using arbitrary file12 loaders, such as ``toml.load`` or ``json.load``.439 unmodified lines452 Released 2016-05-29, codename Absinthe453 454 - Added support to serializing top-level arrays to455 :func:`flask.jsonify`. This introduces a security risk in ancient455- browsers. See :ref:`json-security` for details.456+ browsers.457 - Added before_render_template signal.458 - Added ``**kwargs`` to :meth:`flask.Test.test_client` to support459 passing additional keyword arguments to the constructor of460 :attr:`flask.Flask.test_client_class`.106 unmodified lines567 568 Released 2013-06-13, codename Limoncello569 570 - 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.571+ limit the impact an attacker can do if the secret key leaks.572 - Added ``template_test`` methods in addition to the already existing573 ``template_filter`` method family.574 - Added ``template_global`` methods in addition to the already575 existing ``template_filter`` method family.20 unmodified lines596 imported templates by default.597 - Added an option to generate non-ascii encoded JSON which should598 result in less bytes being transmitted over the network. It's599 disabled by default to not cause confusion with existing libraries600- that might expect ``flask.json.dumps`` to return bytestrings by601- default.600+ that might expect ``flask.json.dumps`` to return bytes by default.601 - ``flask.g`` is now stored on the app context instead of the request602 context.603 - ``flask.g`` now gained a ``get()`` method for not erroring out on604 non existing items.155 unmodified lines760 modules are located but also an instance path which is the761 designated place to drop files that are modified at runtime (uploads762 etc.). Also this is conceptually only instance depending and outside763 version control so it's the perfect place to put configuration files765- etc. For more information see :ref:`instance-folders`.764+ etc.765 - Added the ``APPLICATION_ROOT`` configuration variable.766 - Implemented :meth:`~flask.testing.TestClient.session_transaction` to767 easily modify sessions from the test environment.768 - Refactored test client internally. The ``APPLICATION_ROOT``71 unmodified lines840 - Implemented a silent flag for ``config.from_pyfile``.841 - Added ``teardown_request`` decorator, for functions that should run842 at the end of a request regardless of whether an exception occurred.843 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`844+ longer executed when an exception is raised.845 - Implemented :func:`flask.has_request_context`846 - Deprecated ``init_jinja_globals``. Override the847 :meth:`~flask.Flask.create_jinja_environment` method instead to848 achieve the same functionality.8 unmodified lines857 can provide custom error messages from a central hub for certain858 errors that might occur during request processing (for instance859 database connection errors, timeouts from remote resources etc.).860 - Blueprints can provide blueprint specific error handlers.863-- Implemented generic :ref:`views` (class-based views).861+- Implemented generic class-based views.862 863 864 Version 0.6.1865 -------------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 linesmodified:setup.cfg+8 added-10 removed
1-[bdist_wheel]2-universal = true3-1 [tool:pytest]2 testpaths = tests3+filterwarnings =4+ error5 6 [coverage:run]7 branch = True8 source =1 unmodified line10 tests11 12 [coverage:paths]13 source =15- src/flask16- .tox/*/lib/python*/site-packages/flask17- .tox/*/site-packages/flask14+ src15+ */site-packages16 17 [flake8]18 # B = bugbear19 # E = pycodestyle errors20 # F = flake8 pyflakes21 # W = pycodestyle warnings22 # B9 = bugbear opinions23+# ISC = implicit-str-concat25-select = B, E, F, W, B924+select = B, E, F, W, B9, ISC25 ignore =26 # slice notation whitespace, invalid27 E20328 # import at top, too many circular import fixes6 unmodified lines35 W50336 # up to 88 allowed by bugbear B95037 max-line-length = 8038 per-file-ignores =40- # __init__ modules export names41- **/__init__.py: F40142- src/flask/_compat.py: E731, B301, F40139+ # __init__ module exports names40+ src/flask/__init__.py: F401modified:setup.py+3 added-13 removed
1-import io1 import re2 3 from setuptools import find_packages4 from setuptools import setup5 7-with io.open("README.rst", "rt", encoding="utf8") as f:6+with open("README.rst", encoding="utf8") as f:7 readme = f.read()8 10-with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f:9+with open("src/flask/__init__.py", encoding="utf8") as f:10 version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)11 12 setup(13 name="Flask",18 unmodified lines32 "Intended Audience :: Developers",33 "License :: OSI Approved :: BSD License",34 "Operating System :: OS Independent",35 "Programming Language :: Python",37- "Programming Language :: Python :: 2",38- "Programming Language :: Python :: 2.7",39- "Programming Language :: Python :: 3",40- "Programming Language :: Python :: 3.5",41- "Programming Language :: Python :: 3.6",42- "Programming Language :: Python :: 3.7",43- "Programming Language :: Python :: 3.8",44- "Programming Language :: Python :: Implementation :: CPython",45- "Programming Language :: Python :: Implementation :: PyPy",36 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",37 "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",38 "Topic :: Software Development :: Libraries :: Application Frameworks",39 "Topic :: Software Development :: Libraries :: Python Modules",40 ],41 packages=find_packages("src"),42 package_dir={"": "src"},43 include_package_data=True,54- python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",44+ python_requires=">=3.6",45 install_requires=[46 "Werkzeug>=0.15",47 "Jinja2>=2.10.1",48 "itsdangerous>=0.24",22 unmodified linesmodified:tox.ini+4 added-31 removed
1 [tox]2 envlist =3- py{38,37,36,35,27,py3,py}3+ py{38,37,36,py3}4 py38-{simplejson,devel,lowest}5+ style6 docs6- coverage7 skip_missing_interpreters = true8 9 [testenv]10-passenv = LANG10 deps =11 pytest13- coverage12 greenlet13 blinker14 python-dotenv15 10 unmodified lines26 27 simplejson: simplejson28 29 commands =32- # the examples need to be installed to test successfully30 pip install -q -e examples/tutorial[test]31 pip install -q -e examples/javascript[test]32 36- # pytest-cov doesn't seem to play nice with -p37- coverage run -p -m pytest --tb=short -Werror {posargs:tests examples}33+ pytest --tb=short --basetemp={envtmpdir} {posargs:tests examples}34 39-[testenv:nightly]40-# courtesy Python nightly test, don't fail the build in CI41-ignore_outcome = true42-commands =43- coverage run -p -m pytest --tb=short -Werror --junitxml=test-results.xml tests44-35 [testenv:style]36 deps = pre-commit37 skip_install = true38 commands = pre-commit run --all-files --show-diff-on-failure39 40 [testenv:docs]51-deps =52- -r docs/requirements.txt41+deps = -r docs/requirements.txt42 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html54-55-[testenv:coverage]56-deps = coverage57-skip_install = true58-commands =59- coverage combine60- coverage html61- coverage report62-63-[testenv:coverage-ci]64-deps = coverage65-skip_install = true66-commands =67- coverage combine68- coverage xml69- coverage report