Skip to content
Myr

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

84 files+583 added−2049 removed

modified:docs/deploying/mod_wsgi.rst-5 removed
209 unmodified lines
210211Add the following lines to the top of your ``.wsgi`` file::212213 activate_this = '/path/to/env/bin/activate_this.py'214 execfile(activate_this, dict(__file__=activate_this))215216For Python 3 add the following lines to the top of your ``.wsgi`` file::217218 activate_this = '/path/to/env/bin/activate_this.py'214 with open(activate_this) as file_:215 exec(file_.read(), dict(__file__=activate_this))216217This sets up the load paths according to the settings of the virtual
1 unmodified line
modified:docs/patterns/distribute.rst-4 removed
17 unmodified lines
18 declare an "entry point" that another package can hook into to extend the19 other package.20- **installation manager**: :command:`pip` can install other libraries for you.2122If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org,23you will already have pip and setuptools on your system. Otherwise, you24will need to install them yourself.2522Flask itself, and all the libraries you can find on PyPI are distributed with23either setuptools or distutils.2425In this case we assume your application is called
148 unmodified lines
modified:docs/patterns/flashing.rst+1 added-1 removed
101 unmodified lines
102103To flash a message with a different category, just use the second argument104to the :func:`~flask.flash` function::105106 flash(u'Invalid password provided', 'error')106 flash('Invalid password provided', 'error')107108Inside the template you then have to tell the109:func:`~flask.get_flashed_messages` function to also return the110categories. The loop looks slightly different in that situation then:
40 unmodified lines
modified:docs/patterns/lazyloading.rst+1 added-1 removed
91 unmodified lines
92:meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::9495 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)99100 # add a single route to the index view
9 unmodified lines
modified:docs/patterns/requestchecksum.rst+1 added-1 removed
50 unmodified lines
51 # 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 lines
38 from sqlalchemy import create_engine39 from sqlalchemy.orm import scoped_session, sessionmaker40 from sqlalchemy.ext.declarative import declarative_base4142 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)42 engine = create_engine('sqlite:////tmp/test.db')43 db_session = scoped_session(sessionmaker(autocommit=False,44 autoflush=False,45 bind=engine))46 Base = declarative_base()
56 unmodified lines
103104Querying is simple as well:105106>>> 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'>110111.. _SQLAlchemy: https://www.sqlalchemy.org/112.. _declarative:113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/
12 unmodified lines
126127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129130 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)130 engine = create_engine('sqlite:////tmp/test.db')131 metadata = MetaData()132 db_session = scoped_session(sessionmaker(autocommit=False,133 autoflush=False,134 bind=engine))
43 unmodified lines
178you basically only need the engine::179180 from sqlalchemy import create_engine, MetaData, Table181182 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)182 engine = create_engine('sqlite:////tmp/test.db')183 metadata = MetaData(bind=engine)184185Then you can either declare the tables in your code like in the examples186above, or automatically load them::
12 unmodified lines
199200To query your database, you use the engine directly or use a connection:201202>>> users.select(users.c.id == 1).execute().first()203(1, u'admin', u'admin@localhost')203(1, 'admin', 'admin@localhost')204205These results are also dict-like tuples:206207>>> r = users.select(users.c.id == 1).execute().first()208>>> r['name']209u'admin'209'admin'210211You can also pass strings of SQL statements to the212:meth:`~sqlalchemy.engine.base.Connection.execute` method:213214>>> engine.execute('select * from users where id = :1', [1]).first()215(1, u'admin', u'admin@localhost')215(1, 'admin', 'admin@localhost')216217For more information about SQLAlchemy, head over to the218`website <https://www.sqlalchemy.org/>`_.
modified:docs/patterns/streaming.rst+1 added-1 removed
19 unmodified lines
20 @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')2627Each ``yield`` expression is directly sent to the browser. Note though28that some WSGI middlewares might break streaming, so be careful there in
56 unmodified lines
modified:docs/patterns/viewdecorators.rst+1 added-2 removed
140 unmodified lines
141 @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 lines
modified:docs/patterns/wtforms.rst+3 added-3 removed
96 unmodified lines
97This macro accepts a couple of keyword arguments that are forwarded to98WTForm's field function, which renders the field for us. The keyword99arguments will be inserted as HTML attributes. So, for example, you can100call ``render_field(form.username, class='username')`` to add a class to101the input element. Note that WTForms returns standard Python unicode102strings, so we have to tell Jinja2 that this data is already HTML-escaped103with the ``|safe`` filter.101the input element. Note that WTForms returns standard Python strings,102so we have to tell Jinja2 that this data is already HTML-escaped with103the ``|safe`` filter.104105Here is the :file:`register.html` template for the function we used above, which106takes advantage of the :file:`_formhelpers.html` template:107
19 unmodified lines
modified:docs/tutorial/blog.rst+1 added-1 removed
205 unmodified lines
206 (id,)207 ).fetchone()208209 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.")211212 if check_author and post['author_id'] != g.user['id']:213 abort(403)214
122 unmodified lines
modified:docs/tutorial/tests.rst+2 added-2 removed
299 unmodified lines
300URL when the register view redirects to the login view.301302:attr:`~Response.data` contains the body of the response as bytes. If303you expect a certain value to render on the page, check that it's in304``data``. Bytes must be compared to bytes. If you want to compare305Unicode text, use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`304``data``. Bytes must be compared to bytes. If you want to compare text,305use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`306instead.307308``pytest.mark.parametrize`` tells Pytest to run the same test function309with different arguments. You use it here to test different invalid
252 unmodified lines
modified:docs/tutorial/views.rst+1 added-1 removed
92 unmodified lines
93 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."9899 if error is None:100 db.execute(101 'INSERT INTO user (username, password) VALUES (?, ?)',
200 unmodified lines
modified:docs/api.rst+6 added-6 removed
56 unmodified lines
57 In this case the values of the above mentioned attributes would be58 the following:5960 ============= ======================================================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 ============= ======================================================686970.. attribute:: request
764 unmodified lines
modified:docs/conf.py+4 added-6 removed
50 unmodified lines
51singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}52html_static_path = ["_static"]53html_favicon = "_static/flask-icon.png"54html_logo = "_static/flask-icon.png"55html_title = "Flask Documentation ({})".format(version)55html_title = f"Flask Documentation ({version})"56html_show_sourcelink = False5758# LaTeX ----------------------------------------------------------------5960latex_documents = [61 (master_doc, "Flask-{}.tex".format(version), html_title, author, "manual")62]60latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")]6162# Local Extensions -----------------------------------------------------6364
8 unmodified lines
73 else:74 words = None7576 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}"8081 if words is None:82 words = url83
11 unmodified lines
modified:docs/config.rst+9 added-9 removed
159 unmodified lines
160.. py:data:: SECRET_KEY161162 A secret key that will be used for securely signing the session cookie163 and can be used for any other security related needs by extensions or your164 application. It should be a long random string of bytes, although unicode165 is accepted too. For example, copy the output of this to your config::164 application. It should be a long random ``bytes`` or ``str``. For165 example, copy the output of this to your config::166167 $ python -c 'import os; print(os.urandom(16))'168 b'_5#y2L"F4Q8z\n\xec]/'169
131 unmodified lines
301 Default: ``None``302303.. py:data:: JSON_AS_ASCII304305 Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON306 will be returned as a Unicode string, or encoded as ``UTF-8`` by307 ``jsonify``. This has security implications when rendering the JSON into308 JavaScript in templates, and should typically remain enabled.305 Serialize objects to ASCII-encoded JSON. If this is disabled, the306 JSON returned from ``jsonify`` will contain Unicode characters. This307 has security implications when rendering the JSON into JavaScript in308 templates, and should typically remain enabled.309310 Default: ``True``311312.. py:data:: JSON_SORT_KEYS
282 unmodified lines
595 TESTING = False596 DB_SERVER = '192.168.1.56'597598 @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"601602 class ProductionConfig(Config):603 """Uses production database server."""604 DB_SERVER = '192.168.19.32'
72 unmodified lines
677 /instance678679- Installed module or package::680681 $PREFIX/lib/python2.X/site-packages/myapp681 $PREFIX/lib/pythonX.Y/site-packages/myapp682 $PREFIX/var/myapp-instance683684 ``$PREFIX`` is the prefix of your Python installation. This can be685 ``/usr`` or the path to your virtualenv. You can print the value of
32 unmodified lines
modified:docs/design.rst+8 added-8 removed
107 unmodified lines
108has a certain understanding about how things work. On the surface they109all work the same: you tell the engine to evaluate a template with a set110of variables and take the return value as string.111112But that's about where similarities end. Jinja2 for example has an113extensive filter system, a certain way to do template inheritance, support114for reusable blocks (macros) that can be used from inside templates and115also from Python code, uses Unicode for all operations, supports116iterative template rendering, configurable syntax and more. On the other117hand an engine like Genshi is based on XML stream evaluation, template118inheritance by taking the availability of XPath into account and more.119Mako on the other hand treats templates similar to Python modules.112But that's about where similarities end. Jinja2 for example has an113extensive filter system, a certain way to do template inheritance,114support for reusable blocks (macros) that can be used from inside115templates and also from Python code, supports iterative template116rendering, configurable syntax and more. On the other hand an engine117like Genshi is based on XML stream evaluation, template inheritance by118taking the availability of XPath into account and more. Mako on the119other hand treats templates similar to Python modules.120121When it comes to connecting a template engine with an application or122framework there is more than just rendering templates. For instance,123Flask uses Jinja2's extensive autoescaping support. Also it provides
68 unmodified lines
modified:docs/index.rst-3 removed
82 unmodified lines
8384 design85 htmlfaq86 security87 unicode87 extensiondev89 styleguide90 upgrading88 changelog89 license90 contributing
modified:docs/installation.rst+13 added-72 removed
1 unmodified line
23Installation4============567Python Version8--------------99We recommend using the latest version of Python 3. Flask supports Python 3.510and newer, Python 2.7, and PyPy.10We recommend using the latest version of Python. Flask supports Python113.6 and newer.121314Dependencies15------------1617These distributions will be installed automatically when installing Flask.
14 unmodified lines
32.. _MarkupSafe: https://palletsprojects.com/p/markupsafe/33.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/34.. _Click: https://palletsprojects.com/p/click/353637Optional dependencies38~~~~~~~~~~~~~~~~~~~~~3940These distributions will not be installed automatically. Flask will detect and
12 unmodified lines
53.. _SimpleJSON: https://simplejson.readthedocs.io/54.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme55.. _watchdog: https://pythonhosted.org/watchdog/565758Virtual environments59--------------------6061Use a virtual environment to manage the dependencies for your project, both in
7 unmodified lines
69Virtual environments are independent groups of Python libraries, one for each70project. Packages installed for one project will not affect other projects or71the operating system's packages.7269Python 3 comes bundled with the :mod:`venv` module to create virtual70environments. If you're using a modern version of Python, you can continue on71to the next section.73Python comes bundled with the :mod:`venv` module to create virtual74environments.7573If you're using Python 2, see :ref:`install-install-virtualenv` first.7675.. _install-create-env:7677Create an environment78~~~~~~~~~~~~~~~~~~~~~7980Create a project folder and a :file:`venv` folder within:
9 unmodified lines
90.. code-block:: bat9192 $ py -3 -m venv venv9394If you needed to install virtualenv because you are using Python 2, use95the following command instead:9497.. code-block:: sh9899 $ python2 -m virtualenv venv100101On Windows:102103.. code-block:: bat104105 > \Python27\Scripts\virtualenv.exe venv10695.. _install-activate-env:9697Activate the environment98~~~~~~~~~~~~~~~~~~~~~~~~
9 unmodified lines
108.. code-block:: bat109110 > venv\Scripts\activate111124Your shell prompt will change to show the name of the activated environment.112Your shell prompt will change to show the name of the activated113environment.114115116Install Flask117-------------118129Within the activated environment, use the following command to install Flask:119Within the activated environment, use the following command to install120Flask:121122.. code-block:: sh123124 $ pip install Flask125126Flask is now installed. Check out the :doc:`/quickstart` or go to the127:doc:`Documentation Overview </index>`.137138Living on the edge139~~~~~~~~~~~~~~~~~~140141If you want to work with the latest Flask code before it's released, install or142update the code from the master branch:143144.. code-block:: sh145146 $ pip install -U https://github.com/pallets/flask/archive/master.tar.gz147148.. _install-install-virtualenv:149150Install virtualenv151------------------152153If you are using Python 2, the venv module is not available. Instead,154install `virtualenv`_.155156On Linux, virtualenv is provided by your package manager:157158.. code-block:: sh159160 # Debian, Ubuntu161 $ sudo apt-get install python-virtualenv162163 # CentOS, Fedora164 $ sudo yum install python-virtualenv165166 # Arch167 $ sudo pacman -S python-virtualenv168169If you are on Mac OS X or Windows, download `get-pip.py`_, then:170171.. code-block:: sh172173 $ sudo python2 Downloads/get-pip.py174 $ sudo python2 -m pip install virtualenv175176On Windows, as an administrator:177178.. code-block:: bat179180 > \Python27\python.exe Downloads\get-pip.py181 > \Python27\python.exe -m pip install virtualenv182183Now you can return above and :ref:`install-create-env`.184185.. _virtualenv: https://virtualenv.pypa.io/186.. _get-pip.py: https://bootstrap.pypa.io/get-pip.py
modified:docs/quickstart.rst+6 added-7 removed
291 unmodified lines
2922931. Reversing is often more descriptive than hard-coding the URLs.2942. You can change your URLs in one go instead of needing to remember to295 manually change hard-coded URLs.2963. URL building handles escaping of special characters and Unicode data297 transparently.2963. URL building handles escaping of special characters transparently.2974. The generated paths are always absolute, avoiding unexpected behavior298 of relative paths in browsers.2995. If your application is placed outside the URL root, for example, in300 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly
145 unmodified lines
446Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::447448 >>> from markupsafe import Markup449 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'451 Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')450 Markup('<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')451 >>> Markup.escape('<blink>hacker</blink>')453 Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')452 Markup('&lt;blink&gt;hacker&lt;/blink&gt;')453 >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()455 u'Marked up \xbb HTML'454 'Marked up \xbb HTML'455456.. versionchanged:: 0.5457458 Autoescaping is no longer enabled for all templates. The following
149 unmodified lines
608609 @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 ...615616For some better examples, checkout the :ref:`uploading-files` pattern.617
304 unmodified lines
deleted:docs/styleguide.rst-200 removed
1Pocoo Styleguide2================34The Pocoo styleguide is the styleguide for all Pocoo Projects, including5Flask. This styleguide is a requirement for Patches to Flask and a6recommendation for Flask extensions.78In general the Pocoo Styleguide closely follows :pep:`8` with some small9differences and extensions.1011General Layout12--------------1314Indentation:15 4 real spaces. No tabs, no exceptions.1617Maximum line length:18 79 characters with a soft limit for 84 if absolutely necessary. Try19 to avoid too nested code by cleverly placing `break`, `continue` and20 `return` statements.2122Continuing long statements:23 To continue a statement you can use backslashes in which case you should24 align the next line with the last dot or equal sign, or indent four25 spaces::2627 this_is_a_very_long(function_call, 'with many parameters') \28 .that_returns_an_object_with_an_attribute2930 MyModel.query.filter(MyModel.scalar > 120) \31 .order_by(MyModel.name.desc()) \32 .limit(10)3334 If you break in a statement with parentheses or braces, align to the35 braces::3637 this_is_a_very_long(function_call, 'with many parameters',38 23, 42, 'and even more')3940 For lists or tuples with many items, break immediately after the41 opening brace::4243 items = [44 'this is the first', 'set of items', 'with more items',45 'to come in this line', 'like this'46 ]4748Blank lines:49 Top level functions and classes are separated by two lines, everything50 else by one. Do not use too many blank lines to separate logical51 segments in code. Example::5253 def hello(name):54 print f'Hello {name}!'555657 def goodbye(name):58 print f'See you {name}.'596061 class MyClass(object):62 """This is a simple docstring"""6364 def __init__(self, name):65 self.name = name6667 def get_annoying_name(self):68 return self.name.upper() + '!!!!111'6970Expressions and Statements71--------------------------7273General whitespace rules:74 - No whitespace for unary operators that are not words75 (e.g.: ``-``, ``~`` etc.) as well on the inner side of parentheses.76 - Whitespace is placed between binary operators.7778 Good::7980 exp = -1.0581 value = (item_value / item_count) * offset / exp82 value = my_list[index]83 value = my_dict['key']8485 Bad::8687 exp = - 1.0588 value = ( item_value / item_count ) * offset / exp89 value = (item_value/item_count)*offset/exp90 value=( item_value/item_count ) * offset/exp91 value = my_list[ index ]92 value = my_dict ['key']9394Yoda statements are a no-go:95 Never compare constant with variable, always variable with constant:9697 Good::9899 if method == 'md5':100 pass101102 Bad::103104 if 'md5' == method:105 pass106107Comparisons:108 - against arbitrary types: ``==`` and ``!=``109 - against singletons with ``is`` and ``is not`` (eg: ``foo is not110 None``)111 - never compare something with ``True`` or ``False`` (for example never112 do ``foo == False``, do ``not foo`` instead)113114Negated containment checks:115 use ``foo not in bar`` instead of ``not foo in bar``116117Instance checks:118 ``isinstance(a, C)`` instead of ``type(A) is C``, but try to avoid119 instance checks in general. Check for features.120121122Naming Conventions123------------------124125- Class names: ``CamelCase``, with acronyms kept uppercase (``HTTPWriter``126 and not ``HttpWriter``)127- Variable names: ``lowercase_with_underscores``128- Method and function names: ``lowercase_with_underscores``129- Constants: ``UPPERCASE_WITH_UNDERSCORES``130- precompiled regular expressions: ``name_re``131132Protected members are prefixed with a single underscore. Double133underscores are reserved for mixin classes.134135On classes with keywords, trailing underscores are appended. Clashes with136builtins are allowed and **must not** be resolved by appending an137underline to the variable name. If the function needs to access a138shadowed builtin, rebind the builtin to a different name instead.139140Function and method arguments:141 - class methods: ``cls`` as first parameter142 - instance methods: ``self`` as first parameter143 - lambdas for properties might have the first parameter replaced144 with ``x`` like in ``display_name = property(lambda x: x.real_name145 or x.username)``146147148Docstrings149----------150151Docstring conventions:152 All docstrings are formatted with reStructuredText as understood by153 Sphinx. Depending on the number of lines in the docstring, they are154 laid out differently. If it's just one line, the closing triple155 quote is on the same line as the opening, otherwise the text is on156 the same line as the opening quote and the triple quote that closes157 the string on its own line::158159 def foo():160 """This is a simple docstring"""161162163 def bar():164 """This is a longer docstring with so much information in there165 that it spans three lines. In this case the closing triple quote166 is on its own line.167 """168169Module header:170 The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173174 # -*- coding: utf-8 -*-175 """176 package.module177 ~~~~~~~~~~~~~~178179 A brief description goes here.180181 :copyright: (c) YEAR by AUTHOR.182 :license: LICENSE_NAME, see LICENSE_FILE for more details.183 """184185 Please keep in mind that proper copyrights and license files are a186 requirement for approved Flask extensions.187188189Comments190--------191192Rules for comments are similar to docstrings. Both are formatted with193reStructuredText. If a comment is used to document an attribute, put a194colon after the opening pound sign (``#``)::195196 class User(object):197 #: the name of the user as unicode string198 name = Column(String)199 #: the sha1 hash of the password + inline salt200 pw_hash = Column(String)
modified:docs/templating.rst+2 added-2 removed
220 unmodified lines
221functions)::222223 @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)228229The context processor above makes the `format_price` function available to all230templates::
6 unmodified lines
modified:docs/testing.rst+6 added-3 removed
163 unmodified lines
164165 def test_login_logout(client):166 """Make sure login and logout works."""167168 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])168 username = flaskr.app.config["USERNAME"]169 password = flaskr.app.config["PASSWORD"]170171 rv = login(client, username, password)172 assert b'You were logged in' in rv.data173174 rv = logout(client)175 assert b'You were logged out' in rv.data176174 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.data179177 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.data182183Test Adding Messages184--------------------
280 unmodified lines
deleted:docs/unicode.rst-107 removed
1Unicode in Flask2================34Flask, like Jinja2 and Werkzeug, is totally Unicode based when it comes to5text. Not only these libraries, also the majority of web related Python6libraries that deal with text. If you don't know Unicode so far, you7should probably read `The Absolute Minimum Every Software Developer8Absolutely, Positively Must Know About Unicode and Character Sets9<https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/>`_.10This part of the documentation just tries to cover the very basics so11that you have a pleasant experience with Unicode related things.1213Automatic Conversion14--------------------1516Flask has a few assumptions about your application (which you can change17of course) that give you basic and painless Unicode support:1819- the encoding for text on your website is UTF-820- internally you will always use Unicode exclusively for text except21 for literal strings with only ASCII character points.22- encoding and decoding happens whenever you are talking over a protocol23 that requires bytes to be transmitted.2425So what does this mean to you?2627HTTP is based on bytes. Not only the protocol, also the system used to28address documents on servers (so called URIs or URLs). However HTML which29is usually transmitted on top of HTTP supports a large variety of30character sets and which ones are used, are transmitted in an HTTP header.31To not make this too complex Flask just assumes that if you are sending32Unicode out you want it to be UTF-8 encoded. Flask will do the encoding33and setting of the appropriate headers for you.3435The same is true if you are talking to databases with the help of36SQLAlchemy or a similar ORM system. Some databases have a protocol that37already transmits Unicode and if they do not, SQLAlchemy or your other ORM38should take care of that.3940The Golden Rule41---------------4243So the rule of thumb: if you are not dealing with binary data, work with44Unicode. What does working with Unicode in Python 2.x mean?4546- as long as you are using ASCII code points only (basically numbers,47 some special characters of Latin letters without umlauts or anything48 fancy) you can use regular string literals (``'Hello World'``).49- if you need anything else than ASCII in a string you have to mark50 this string as Unicode string by prefixing it with a lowercase `u`.51 (like ``u'Hänsel und Gretel'``)52- if you are using non-Unicode characters in your Python files you have53 to tell Python which encoding your file uses. Again, I recommend54 UTF-8 for this purpose. To tell the interpreter your encoding you can55 put the ``# -*- coding: utf-8 -*-`` into the first or second line of56 your Python source file.57- Jinja is configured to decode the template files from UTF-8. So make58 sure to tell your editor to save the file as UTF-8 there as well.5960Encoding and Decoding Yourself61------------------------------6263If you are talking with a filesystem or something that is not really based64on Unicode you will have to ensure that you decode properly when working65with Unicode interface. So for example if you want to load a file on the66filesystem and embed it into a Jinja2 template you will have to decode it67from the encoding of that file. Here the old problem that text files do68not specify their encoding comes into play. So do yourself a favour and69limit yourself to UTF-8 for text files as well.7071Anyways. To load such a file with Unicode you can use the built-in72:meth:`str.decode` method::7374 def read_file(filename, charset='utf-8'):75 with open(filename, 'r') as f:76 return f.read().decode(charset)7778To go from Unicode into a specific charset such as UTF-8 you can use the79:meth:`unicode.encode` method::8081 def write_file(filename, contents, charset='utf-8'):82 with open(filename, 'w') as f:83 f.write(contents.encode(charset))8485Configuring Editors86-------------------8788Most editors save as UTF-8 by default nowadays but in case your editor is89not configured to do this you have to change it. Here some common ways to90set your editor to store as UTF-8:9192- Vim: put ``set enc=utf-8`` to your ``.vimrc`` file.9394- Emacs: either use an encoding cookie or put this into your ``.emacs``95 file::9697 (prefer-coding-system 'utf-8)98 (setq default-buffer-file-coding-system 'utf-8)99100- Notepad++:101102 1. Go to *Settings -> Preferences ...*103 2. Select the "New Document/Default Directory" tab104 3. Select "UTF-8 without BOM" as encoding105106 It is also recommended to use the Unix newline format, you can select107 it in the same panel but this is not a requirement.
deleted:docs/upgrading.rst-472 removed
1Upgrading to Newer Releases2===========================34Flask itself is changing like any software is changing over time. Most of5the changes are the nice kind, the kind where you don't have to change6anything in your code to profit from a new release.78However every once in a while there are changes that do require some9changes in your code or there are changes that make it possible for you to10improve your own code quality by taking advantage of new features in11Flask.1213This section of the documentation enumerates all the changes in Flask from14release to release and how you can change your code to have a painless15updating experience.1617Use the :command:`pip` command to upgrade your existing Flask installation by18providing the ``--upgrade`` parameter::1920 $ pip install --upgrade Flask2122.. _upgrading-to-012:2324Version 0.1225------------2627Changes to send_file28````````````````````2930The ``filename`` is no longer automatically inferred from file-like objects.31This means that the following code will no longer automatically have32``X-Sendfile`` support, etag generation or MIME-type guessing::3334 response = send_file(open('/path/to/file.txt'))3536Any of the following is functionally equivalent::3738 fname = '/path/to/file.txt'3940 # Just pass the filepath directly41 response = send_file(fname)4243 # Set the MIME-type and ETag explicitly44 response = send_file(open(fname), mimetype='text/plain')45 response.set_etag(...)4647 # Set `attachment_filename` for MIME-type guessing48 # ETag still needs to be manually set49 response = send_file(open(fname), attachment_filename=fname)50 response.set_etag(...)5152The reason for this is that some file-like objects have an invalid or even53misleading ``name`` attribute. Silently swallowing errors in such cases was not54a satisfying solution.5556Additionally the default of falling back to ``application/octet-stream`` has57been restricted. If Flask can't guess one or the user didn't provide one, the58function fails if no filename information was provided.5960.. _upgrading-to-011:6162Version 0.1163------------64650.11 is an odd release in the Flask release cycle because it was supposed66to be the 1.0 release. However because there was such a long lead time up67to the release we decided to push out a 0.11 release first with some68changes removed to make the transition easier. If you have been tracking69the master branch which was 1.0 you might see some unexpected changes.7071In case you did track the master branch you will notice that72:command:`flask --app` is removed now.73You need to use the environment variable to specify an application.7475Debugging76`````````7778Flask 0.11 removed the ``debug_log_format`` attribute from Flask79applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can80be used to disable the default log handlers and custom log handlers can be81set up.8283Error handling84``````````````8586The behavior of error handlers was changed.87The precedence of handlers used to be based on the decoration/call order of88:meth:`~flask.Flask.errorhandler` and89:meth:`~flask.Flask.register_error_handler`, respectively.90Now the inheritance hierarchy takes precedence and handlers for more91specific exception classes are executed instead of more general ones.92See :ref:`error-handlers` for specifics.9394Trying to register a handler on an instance now raises :exc:`ValueError`.9596.. note::9798 There used to be a logic error allowing you to register handlers99 only for exception *instances*. This was unintended and plain wrong,100 and therefore was replaced with the intended behavior of registering101 handlers only using exception classes and HTTP error codes.102103Templating104``````````105106The :func:`~flask.templating.render_template_string` function has changed to107autoescape template variables by default. This better matches the behavior108of :func:`~flask.templating.render_template`.109110Extension imports111`````````````````112113Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114``flask_foo``.115116The old form still works, but Flask will issue a117``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118way. We also provide a migration utility called `flask-ext-migrate119<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to120automatically rewrite your imports for this.121122.. _upgrading-to-010:123124Version 0.10125------------126127The biggest change going from 0.9 to 0.10 is that the cookie serialization128format changed from pickle to a specialized JSON format. This change has129been done in order to avoid the damage an attacker can do if the secret130key is leaked. When you upgrade you will notice two major changes: all131sessions that were issued before the upgrade are invalidated and you can132only store a limited amount of types in the session. The new sessions are133by design much more restricted to only allow JSON with a few small134extensions for tuples and strings with HTML markup.135136In order to not break people's sessions it is possible to continue using137the old session system by using the `Flask-OldSessions`_ extension.138139Flask also started storing the :data:`flask.g` object on the application140context instead of the request context. This change should be transparent141for you but it means that you now can store things on the ``g`` object142when there is no request context yet but an application context. The old143``flask.Flask.request_globals_class`` attribute was renamed to144:attr:`flask.Flask.app_ctx_globals_class`.145146.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147148Version 0.9149-----------150151The behavior of returning tuples from a function was simplified. If you152return a tuple it no longer defines the arguments for the response object153you're creating, it's now always a tuple in the form ``(response, status,154headers)`` where at least one item has to be provided. If you depend on155the old behavior, you can add it easily by subclassing Flask::156157 class TraditionalFlask(Flask):158 def make_response(self, rv):159 if isinstance(rv, tuple):160 return self.response_class(*rv)161 return Flask.make_response(self, rv)162163If you maintain an extension that was using :data:`~flask._request_ctx_stack`164before, please consider changing to :data:`~flask._app_ctx_stack` if it makes165sense for your extension. For instance, the app context stack makes sense for166extensions which connect to databases. Using the app context stack instead of167the request context stack will make extensions more readily handle use cases168outside of requests.169170Version 0.8171-----------172173Flask introduced a new session interface system. We also noticed that174there was a naming collision between ``flask.session`` the module that175implements sessions and :data:`flask.session` which is the global session176object. With that introduction we moved the implementation details for177the session system into a new module called :mod:`flask.sessions`. If you178used the previously undocumented session support we urge you to upgrade.179180If invalid JSON data was submitted Flask will now raise a181:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the182default :exc:`ValueError` bubble up. This has the advantage that you no183longer have to handle that error to avoid an internal server error showing184up for the user. If you were catching this down explicitly in the past185as :exc:`ValueError` you will need to change this.186187Due to a bug in the test client Flask 0.7 did not trigger teardown188handlers when the test client was used in a with statement. This was189since fixed but might require some changes in your test suites if you190relied on this behavior.191192Version 0.7193-----------194195In Flask 0.7 we cleaned up the code base internally a lot and did some196backwards incompatible changes that make it easier to implement larger197applications with Flask. Because we want to make upgrading as easy as198possible we tried to counter the problems arising from these changes by199providing a script that can ease the transition.200201The script scans your whole application and generates a unified diff with202changes it assumes are safe to apply. However as this is an automated203tool it won't be able to find all use cases and it might miss some. We204internally spread a lot of deprecation warnings all over the place to make205it easy to find pieces of code that it was unable to upgrade.206207We strongly recommend that you hand review the generated patchfile and208only apply the chunks that look good.209210If you are using git as version control system for your project we211recommend applying the patch with ``path -p1 < patchfile.diff`` and then212using the interactive commit feature to only apply the chunks that look213good.214215To apply the upgrade script do the following:2162171. Download the script: `flask-07-upgrade.py218 <https://raw.githubusercontent.com/pallets/flask/0.12.3/scripts/flask-07-upgrade.py>`_2192. Run it in the directory of your application::220221 $ python flask-07-upgrade.py > patchfile.diff2222233. Review the generated patchfile.2244. Apply the patch::225226 $ patch -p1 < patchfile.diff2272285. If you were using per-module template folders you need to move some229 templates around. Previously if you had a folder named :file:`templates`230 next to a blueprint named ``admin`` the implicit template path231 automatically was :file:`admin/index.html` for a template file called232 :file:`templates/index.html`. This no longer is the case. Now you need233 to name the template :file:`templates/admin/index.html`. The tool will234 not detect this so you will have to do that on your own.235236Please note that deprecation warnings are disabled by default starting237with Python 2.7. In order to see the deprecation warnings that might be238emitted you have to enabled them with the :mod:`warnings` module.239240If you are working with windows and you lack the ``patch`` command line241utility you can get it as part of various Unix runtime environments for242windows including cygwin, msysgit or ming32. Also source control systems243like svn, hg or git have builtin support for applying unified diffs as244generated by the tool. Check the manual of your version control system245for more information.246247Bug in Request Locals248`````````````````````249250Due to a bug in earlier implementations the request local proxies now251raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they252are unbound. If you caught these exceptions with :exc:`AttributeError`253before, you should catch them with :exc:`RuntimeError` now.254255Additionally the :func:`~flask.send_file` function is now issuing256deprecation warnings if you depend on functionality that will be removed257in Flask 0.11. Previously it was possible to use etags and mimetypes258when file objects were passed. This was unreliable and caused issues259for a few setups. If you get a deprecation warning, make sure to260update your application to work with either filenames there or disable261etag attaching and attach them yourself.262263Old code::264265 return send_file(my_file_object)266 return send_file(my_file_object)267268New code::269270 return send_file(my_file_object, add_etags=False)271272.. _upgrading-to-new-teardown-handling:273274Upgrading to new Teardown Handling275``````````````````````````````````276277We streamlined the behavior of the callbacks for request handling. For278things that modify the response the :meth:`~flask.Flask.after_request`279decorators continue to work as expected, but for things that absolutely280must happen at the end of request we introduced the new281:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that282change also made after-request work differently under error conditions.283It's not consistently skipped if exceptions happen whereas previously it284might have been called twice to ensure it is executed at the end of the285request.286287If you have database connection code that looks like this::288289 @app.after_request290 def after_request(response):291 g.db.close()292 return response293294You are now encouraged to use this instead::295296 @app.teardown_request297 def after_request(exception):298 if hasattr(g, 'db'):299 g.db.close()300301On the upside this change greatly improves the internal code flow and302makes it easier to customize the dispatching and error handling. This303makes it now a lot easier to write unit tests as you can prevent closing304down of database connections for a while. You can take advantage of the305fact that the teardown callbacks are called when the response context is306removed from the stack so a test can query the database after request307handling::308309 with app.test_client() as client:310 resp = client.get('/')311 # g.db is still bound if there is such a thing312313 # and here it's gone314315Manual Error Handler Attaching316``````````````````````````````317318While it is still possible to attach error handlers to319:attr:`Flask.error_handlers` it's discouraged to do so and in fact320deprecated. In general we no longer recommend custom error handler321attaching via assignments to the underlying dictionary due to the more322complex internal handling to support arbitrary exception classes and323blueprints. See :meth:`Flask.errorhandler` for more information.324325The proper upgrade is to change this::326327 app.error_handlers[403] = handle_error328329Into this::330331 app.register_error_handler(403, handle_error)332333Alternatively you should just attach the function with a decorator::334335 @app.errorhandler(403)336 def handle_error(e):337 ...338339(Note that :meth:`register_error_handler` is new in Flask 0.7)340341Blueprint Support342`````````````````343344Blueprints replace the previous concept of “Modules” in Flask. They345provide better semantics for various features and work better with large346applications. The update script provided should be able to upgrade your347applications automatically, but there might be some cases where it fails348to upgrade. What changed?349350- Blueprints need explicit names. Modules had an automatic name351 guessing scheme where the shortname for the module was taken from the352 last part of the import module. The upgrade script tries to guess353 that name but it might fail as this information could change at354 runtime.355- Blueprints have an inverse behavior for :meth:`url_for`. Previously356 ``.foo`` told :meth:`url_for` that it should look for the endpoint357 ``foo`` on the application. Now it means “relative to current module”.358 The script will inverse all calls to :meth:`url_for` automatically for359 you. It will do this in a very eager way so you might end up with360 some unnecessary leading dots in your code if you're not using361 modules.362- Blueprints do not automatically provide static folders. They will363 also no longer automatically export templates from a folder called364 :file:`templates` next to their location however but it can be enabled from365 the constructor. Same with static files: if you want to continue366 serving static files you need to tell the constructor explicitly the367 path to the static folder (which can be relative to the blueprint's368 module path).369- Rendering templates was simplified. Now the blueprints can provide370 template folders which are added to a general template searchpath.371 This means that you need to add another subfolder with the blueprint's372 name into that folder if you want :file:`blueprintname/template.html` as373 the template name.374375If you continue to use the ``Module`` object which is deprecated, Flask will376restore the previous behavior as good as possible. However we strongly377recommend upgrading to the new blueprints as they provide a lot of useful378improvement such as the ability to attach a blueprint multiple times,379blueprint specific error handlers and a lot more.380381382Version 0.6383-----------384385Flask 0.6 comes with a backwards incompatible change which affects the386order of after-request handlers. Previously they were called in the order387of the registration, now they are called in reverse order. This change388was made so that Flask behaves more like people expected it to work and389how other systems handle request pre- and post-processing. If you390depend on the order of execution of post-request functions, be sure to391change the order.392393Another change that breaks backwards compatibility is that context394processors will no longer override values passed directly to the template395rendering function. If for example ``request`` is as variable passed396directly to the template, the default context processor will not override397it with the current request object. This makes it easier to extend398context processors later to inject additional variables without breaking399existing template not expecting them.400401Version 0.5402-----------403404Flask 0.5 is the first release that comes as a Python package instead of a405single module. There were a couple of internal refactoring so if you406depend on undocumented internal details you probably have to adapt the407imports.408409The following changes may be relevant to your application:410411- autoescaping no longer happens for all templates. Instead it is412 configured to only happen on files ending with ``.html``, ``.htm``,413 ``.xml`` and ``.xhtml``. If you have templates with different414 extensions you should override the415 :meth:`~flask.Flask.select_jinja_autoescape` method.416- Flask no longer supports zipped applications in this release. This417 functionality might come back in future releases if there is demand418 for this feature. Removing support for this makes the Flask internal419 code easier to understand and fixes a couple of small issues that make420 debugging harder than necessary.421- The ``create_jinja_loader`` function is gone. If you want to customize422 the Jinja loader now, use the423 :meth:`~flask.Flask.create_jinja_environment` method instead.424425Version 0.4426-----------427428For application developers there are no changes that require changes in429your code. In case you are developing on a Flask extension however, and430that extension has a unittest-mode you might want to link the activation431of that mode to the new ``TESTING`` flag.432433Version 0.3434-----------435436Flask 0.3 introduces configuration support and logging as well as437categories for flashing messages. All these are features that are 100%438backwards compatible but you might want to take advantage of them.439440Configuration Support441`````````````````````442443The configuration support makes it easier to write any kind of application444that requires some sort of configuration. (Which most likely is the case445for any application out there).446447If you previously had code like this::448449 app.debug = DEBUG450 app.secret_key = SECRET_KEY451452You no longer have to do that, instead you can just load a configuration453into the config object. How this works is outlined in :ref:`config`.454455Logging Integration456```````````````````457458Flask now configures a logger for you with some basic and useful defaults.459If you run your application in production and want to profit from460automatic error logging, you might be interested in attaching a proper log461handler. Also you can start logging warnings and errors into the logger462when appropriately. For more information on that, read463:ref:`application-errors`.464465Categories for Flash Messages466`````````````````````````````467468Flash messages can now have categories attached. This makes it possible469to render errors, warnings or regular messages differently for example.470This is an opt-in feature because it requires some rethinking in the code.471472Read all about that in the :ref:`message-flashing-pattern` pattern.
modified:examples/javascript/js_example/__init__.py+1 added-1 removed
1from flask import Flask23app = Flask(__name__)45from js_example import views5from js_example import views # noqa: F401
modified:examples/javascript/js_example/views.py+1 added-1 removed
6 unmodified lines
78@app.route("/", defaults={"js": "plain"})9@app.route("/<any(plain, jquery, fetch):js>")10def index(js):11 return render_template("{0}.html".format(js), js=js)11 return render_template(f"{js}.html", js=js)121314@app.route("/add", methods=["POST"])15def add():
3 unmodified lines
modified:examples/javascript/setup.py+1 added-3 removed
1import io21from setuptools import find_packages2from setuptools import setup36with io.open("README.rst", "rt", encoding="utf8") as f:4with open("README.rst", encoding="utf8") as f:5 readme = f.read()67setup(8 name="js_example",
13 unmodified lines
modified:examples/tutorial/flaskr/auth.py+1 added-1 removed
62 unmodified lines
63 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."6869 if error is None:70 # the name is available, store it in the database and go to71 # the login page
45 unmodified lines
modified:examples/tutorial/flaskr/blog.py+1 added-1 removed
47 unmodified lines
48 .fetchone()49 )5051 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.")5354 if check_author and post["author_id"] != g.user["id"]:55 abort(403)56
69 unmodified lines
modified:examples/tutorial/tests/conftest.py+1 added-1 removed
42 unmodified lines
43 """A test runner for the app's Click commands."""44 return app.test_cli_runner()454647class AuthActions(object):47class AuthActions:48 def __init__(self, client):49 self._client = client5051 def login(self, username="test", password="test"):
11 unmodified lines
modified:examples/tutorial/tests/test_db.py+1 added-1 removed
15 unmodified lines
16 assert "closed" in str(e.value)171819def test_init_db_command(runner, monkeypatch):20 class Recorder(object):20 class Recorder:21 called = False2223 def fake_init_db():24 Recorder.called = True
5 unmodified lines
modified:examples/tutorial/setup.py+1 added-3 removed
1import io21from setuptools import find_packages2from setuptools import setup36with io.open("README.rst", "rt", encoding="utf8") as f:4with open("README.rst", encoding="utf8") as f:5 readme = f.read()67setup(8 name="flaskr",
13 unmodified lines
modified:src/flask/json/__init__.py+10 added-13 removed
1# -*- coding: utf-8 -*-1"""2flask.json3~~~~~~~~~~4
9 unmodified lines
14from itsdangerous import json as _json15from jinja2 import Markup16from werkzeug.http import http_date1719from .._compat import PY220from .._compat import text_type18from ..globals import current_app19from ..globals import request2021try:22 import dataclasses23except ImportError:24 # Python < 3.725 dataclasses = None2627# Figure out if simplejson escapes slashes. This behavior was changed28# from one version to another without reason.
64 unmodified lines
93 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)99100101class JSONDecoder(_json.JSONDecoder):
104 unmodified lines
206 """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 rv213214
38 unmodified lines
253254def 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)259260261def htmlsafe_dumps(obj, **kwargs):
22 unmodified lines
284 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 rv296297298def 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)))301302303def jsonify(*args, **kwargs):304 """This function wraps :func:`dumps` to add a few enhancements that make
58 unmodified lines
363 else:364 data = args or kwargs365366 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 )370371
2 unmodified lines
modified:src/flask/json/tag.py+6 added-9 removed
1# -*- coding: utf-8 -*-1"""2Tagged JSON3~~~~~~~~~~~4
43 unmodified lines
48from jinja2 import Markup49from werkzeug.http import http_date50from werkzeug.http import parse_date5153from .._compat import iteritems54from .._compat import text_type52from ..json import dumps53from ..json import loads545559class JSONTag(object):56class JSONTag:57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""5859 __slots__ = ("serializer",)60
43 unmodified lines
104 )105106 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])}109110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}
7 unmodified lines
120121 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()}125126 tag = to_json127128
48 unmodified lines
177 def check(self, value):178 return callable(getattr(value, "__html__", None))179180 def to_json(self, value):184 return text_type(value.__html__())181 return str(value.__html__())182183 def to_python(self, value):184 return Markup(value)185
25 unmodified lines
211 def to_python(self, value):212 return parse_date(value)213214218class TaggedJSONSerializer(object):215class 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 lines
267 key = tag.key268269 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.")272273 self.tags[key] = tag274275 if index is None:
31 unmodified lines
modified:src/flask/__init__.py+1 added-3 removed
1# -*- coding: utf-8 -*-1"""2 flask3 ~~~~~4
10 unmodified lines
15from werkzeug.exceptions import abort16from werkzeug.utils import redirect1718from . import json20from ._compat import json_available19from .app import Flask20from .app import Request21from .app import Response22from .blueprints import Blueprint
31 unmodified lines
54from .signals import template_rendered55from .templating import render_template56from .templating import render_template_string5760__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 lines
deleted:src/flask/_compat.py-145 removed
1# -*- coding: utf-8 -*-2"""3 flask._compat4 ~~~~~~~~~~~~~56 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.910 :copyright: 2010 Pallets11 :license: BSD-3-Clause12"""13import sys1415PY2 = sys.version_info[0] == 216_identity = lambda x: x1718try: # Python 219 text_type = unicode20 string_types = (str, unicode)21 integer_types = (int, long)22except NameError: # Python 323 text_type = str24 string_types = (str,)25 integer_types = (int,)2627if not PY2:28 iterkeys = lambda d: iter(d.keys())29 itervalues = lambda d: iter(d.values())30 iteritems = lambda d: iter(d.items())3132 from inspect import getfullargspec as getargspec33 from io import StringIO34 import collections.abc as collections_abc3536 def reraise(tp, value, tb=None):37 if value.__traceback__ is not tb:38 raise value.with_traceback(tb)39 raise value4041 implements_to_string = _identity4243else:44 iterkeys = lambda d: d.iterkeys()45 itervalues = lambda d: d.itervalues()46 iteritems = lambda d: d.iteritems()4748 from inspect import getargspec49 from cStringIO import StringIO50 import collections as collections_abc5152 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")5354 def implements_to_string(cls):55 cls.__unicode__ = cls.__str__56 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")57 return cls585960def 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)6869 return type.__new__(metaclass, "temporary_class", (), {})707172# 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.83BROKEN_PYPY_CTXMGR_EXIT = False84if hasattr(sys, "pypy_version_info"):8586 class _Mgr(object):87 def __enter__(self):88 return self8990 def __exit__(self, *args):91 if hasattr(sys, "exc_clear"):92 # Python 3 (PyPy3) doesn't have exc_clear93 sys.exc_clear()9495 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 pass107108109try:110 from os import fspath111except 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 path116117118class _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 = value124125 def _warn(self):126 import warnings127128 warnings.warn(self.message, DeprecationWarning, stacklevel=2)129130 def __eq__(self, other):131 self._warn()132 return other == self.value133134 def __ne__(self, other):135 self._warn()136 return other != self.value137138 def __bool__(self):139 self._warn()140 return self.value141142 __nonzero__ = __bool__143144145json_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 lines
8 :license: BSD-3-Clause9"""10import os11import sys13import warnings12from datetime import timedelta13from functools import update_wrapper14from itertools import chain15from threading import Lock
13 unmodified lines
29from werkzeug.wrappers import BaseResponse3031from . import cli32from . import json35from ._compat import integer_types36from ._compat import reraise37from ._compat import string_types38from ._compat import text_type33from .config import Config34from .config import ConfigAttribute35from .ctx import _AppCtxGlobals36from .ctx import AppContext
147 unmodified lines
184 :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 """192193 #: The class that is used for request objects. See :class:`~flask.Request`194 #: for more information.
389 unmodified lines
584 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 lines
710 """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")715716 def open_instance_resource(self, resource, mode="rb"):717 """Opens a resource from the application's instance folder718 (:attr:`instance_path`). Otherwise works like
340 unmodified lines
1059 from .testing import FlaskCliRunner as cls10601061 return cls(self, **kwargs)10621071 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`.10761077 .. deprecated: 1.01078 Will be removed in 2.0. Use1079 ``session_interface.open_session`` instead.10801081 :param request: an instance of :attr:`request_class`.1082 """10831084 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)10911092 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`.10961097 .. deprecated: 1.01098 Will be removed in 2.0. Use1099 ``session_interface.save_session`` instead.11001101 :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 """11061107 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)11141115 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`.11181119 .. deprecated: 1.01120 Will be removed in 2.0. Use1121 ``session_interface.make_null_session`` instead.11221123 .. versionadded:: 0.71124 """11251126 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)11341063 @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 the
16 unmodified lines
1083 first_registration = False10841085 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 lines
1110 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 lines
1174 # 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}11841185 # Methods that should always be added1186 required_methods = set(getattr(view_func, "required_methods", ()))1187
21 unmodified lines
1209 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_func12171218 def route(self, rule, **options):
54 unmodified lines
12731274 :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 lines
1341 :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 )13491350 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 )13581359 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1360 handlers[exc_class] = f
362 unmodified lines
1723 message.17241725 .. 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.18031727 if isinstance(e, BadRequestKeyError):1728 if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1729 e.show_exception = True17301731 # 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 = ()17381739 if isinstance(e, HTTPException) and not self.trap_http_exception(e):
1 unmodified line
17411742 handler = self._find_error_handler(e)17431744 if handler is None:1822 reraise(exc_type, exc_value, tb)1745 raise17461747 return handler(e)17481749 def handle_exception(self, e):1750 """Handle an exception that did not have an error handler
28 unmodified lines
1779 even for the default 500 response when there is no handler.17801781 .. 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)17851786 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 raise17911872 self.log_exception((exc_type, exc_value, tb))1792 raise e17931794 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 = e
12 unmodified lines
18111812 .. 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 )18171818 def raise_routing_exception(self, request):1819 """Exceptions that are recording during routing are reraised with
127 unmodified lines
1947 must return a response. Returning ``None``, or the view ending1948 without returning, is not allowed. The following types are allowed1949 for ``view_rv``:19502029 ``str`` (``unicode`` in Python 2)1951 ``str``1952 A response object is created with the string encoded to UTF-81953 as the body.19542033 ``bytes`` (``str`` in Python 2)1955 ``bytes``1956 A response object is created with the bytes as the body.19571958 ``dict``1959 A dictionary that will be jsonify'd before being returned.
47 unmodified lines
20072008 # 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 )20152016 # 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 lines
2028 # 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 )20452046 # 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 lines
2108 for func in funcs:2109 func(endpoint, values)21102111 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 rv21242203 # 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 raise21292130 raise error21312132 def preprocess_request(self):2133 """Called before the request is dispatched. Calls
242 unmodified lines
2376 wrapped to applying middleware."""2377 return self.wsgi_app(environ, start_response)23782379 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 lines
16# a singleton sentinel value for parameter defaults17_sentinel = object()181921class BlueprintSetupState(object):20class 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 lines
78 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 )878889class Blueprint(_PackageBoundObject):
155 unmodified lines
245 state = self.make_setup_state(app, options, first_registration)246247 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 lines
modified:src/flask/cli.py+49 added-74 removed
1# -*- coding: utf-8 -*-1"""2 flask.cli3 ~~~~~~~~~4
1 unmodified line
67 :copyright: 2010 Pallets8 :license: BSD-3-Clause9"""11from __future__ import print_function1210import ast11import inspect12import os13import platform
7 unmodified lines
2122import click23from werkzeug.utils import import_string2428from ._compat import getargspec29from ._compat import itervalues30from ._compat import reraise31from ._compat import text_type25from .globals import current_app26from .helpers import get_debug_flag27from .helpers import get_env28from .helpers import get_load_dotenv
26 unmodified lines
55 if isinstance(app, Flask):56 return app5758 # 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)]6061 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 )6970 # 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)7374 if inspect.isfunction(app_factory):75 try:
4 unmodified lines
80 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 )8990 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 )959697def 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.defaults105106 if "script_info" in arg_names:
43 unmodified lines
150 match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)151152 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 )156157 name, args = match.groups()158
4 unmodified lines
163164 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 = ()172173 try:
2 unmodified lines
176 if not _called_with_wrong_args(attr):177 raise178179 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 = attr186187 if isinstance(app, Flask):188 return app189190 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 )194195196def prepare_import(path):
32 unmodified lines
229 __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 return242243 module = sys.modules[module_name]
10 unmodified lines
254255 import werkzeug256 from . import __version__257269 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 lines
273 is_eager=True,274)275276292class DispatchingApp(object):277class 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 lines
311 __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_info316317 def _load_unlocked(self):318 __traceback_hide__ = True # noqa: F841319 self._app = rv = self.loader()
12 unmodified lines
332 rv = self._load_unlocked()333 return rv(environ, start_response)334335351class ScriptInfo(object):336class 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 the
138 unmodified lines
479 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 ())486487 if add_version_option:
83 unmodified lines
571 )572573 kwargs["obj"] = obj574 kwargs.setdefault("auto_envvar_prefix", "FLASK")590 return super(FlaskGroup, self).main(*args, **kwargs)575 return super().main(*args, **kwargs)576577578def _path_is_ancestor(path, other):579 """Take ``other`` and remove the length of ``path`` from it. Then join it
70 unmodified lines
650 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":651 return652653 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}"655656 if not eager_loading:657 message += " (lazy loading)"658659 click.echo(message)660676 click.echo(" * Environment: {0}".format(env))661 click.echo(f" * Environment: {env}")662663 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)670671 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'}")673674675class CertParamType(click.ParamType):676 """Click option type for the ``--cert`` option. Allows either an
32 unmodified lines
709 return value710711 obj = import_string(value, silent=True)712728 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 obj715716 raise717718
2 unmodified lines
721 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)726745 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)749727 if value is not None:728 if is_adhoc:729 raise click.BadParameter(730 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
23 unmodified lines
754 """755756 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]760761762@click.command("run", short_help="Run a development server.")
37 unmodified lines
800 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_info808def run_command(
45 unmodified lines
854 import code855 from .globals import _app_ctx_stack856857 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 = {}864865 # 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)871872 ctx.update(app.make_shell_context())873
76 unmodified lines
modified:src/flask/config.py+13 added-41 removed
1# -*- coding: utf-8 -*-1"""2 flask.config3 ~~~~~~~~~~~~4
4 unmodified lines
9"""10import errno11import os12import types14import warnings1314from werkzeug.utils import import_string1518from ._compat import iteritems19from ._compat import string_types162122class ConfigAttribute(object):17class ConfigAttribute:18 """Makes an attribute forward to the config"""1920 def __init__(self, name, get_converter=None):21 self.__name__ = name
75 unmodified lines
97 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)107108 def from_pyfile(self, filename, silent=False):
15 unmodified lines
124 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 lines
164 using :meth:`from_object`.165166 :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 lines
195196 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 False202208 e.strerror = "Unable to load configuration file (%s)" % e.strerror203 e.strerror = f"Unable to load configuration file ({e.strerror})"204 raise205206 return self.from_mapping(obj)207213 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.216217 :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.220221 .. deprecated:: 2.0222 Use :meth:`from_file` with :meth:`json.load` instead.223224 .. 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 load233234 return self.from_file(filename, load, silent=silent)235208 def from_mapping(self, *mapping, **kwargs):209 """Updates the config like :meth:`update` ignoring items with non-upper210 keys.211
6 unmodified lines
218 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 lines
256257 .. 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 lines
269 rv[key] = v270 return rv271272 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 lines
11from functools import update_wrapper1213from werkzeug.exceptions import HTTPException1416from ._compat import BROKEN_PYPY_CTXMGR_EXIT17from ._compat import reraise15from .globals import _app_ctx_stack16from .globals import _request_ctx_stack17from .signals import appcontext_popped18from .signals import appcontext_pushed
2 unmodified lines
21# a singleton sentinel value for parameter defaults22_sentinel = object()232428class _AppCtxGlobals(object):25class _AppCtxGlobals:26 """A plain object. Used as a namespace for storing data during an27 application context.2829 Creating an app context automatically creates this object, which is
57 unmodified lines
8788 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)939495def after_this_request(f):
102 unmodified lines
198 """199 return _app_ctx_stack.top is not None200201205class AppContext(object):202class 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 created
12 unmodified lines
219220 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)225226 def pop(self, exc=_sentinel):
5 unmodified lines
232 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)238239 def __enter__(self):240 self.push()
1 unmodified line
242243 def __exit__(self, exc_type, exc_value, tb):244 self.pop(exc_value)245251 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:252 reraise(exc_type, exc_value, tb)246254255class RequestContext(object):247class 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 lines
367 self._implicit_app_ctx_stack.append(app_ctx)368 else:369 self._implicit_app_ctx_stack.append(None)370379 if hasattr(sys, "exc_clear"):380 sys.exc_clear()381371 _request_ctx_stack.push(self)372373 # 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 lines
392 .. versionchanged:: 0.9393 Added the `exc` argument.394 """395 app_ctx = self._implicit_app_ctx_stack.pop()396 clear_request = False397398 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)405417 # 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()423406 request_close = getattr(self.request, "close", None)407 if request_close is not None:408 request_close()409 clear_request = True
8 unmodified lines
418 # Get rid of the app as well if necessary.419 if app_ctx is not None:420 app_ctx.pop(exc)421440 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})"425426 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_exception
14 unmodified lines
443 # 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)446466 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:467 reraise(exc_type, exc_value, tb)468447 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 lines
9"""10import os11from warnings import warn1214from ._compat import implements_to_string15from ._compat import text_type13from .app import Flask14from .blueprints import Blueprint15from .globals import _request_ctx_stack16
3 unmodified lines
20 unexpected unicode or binary data.21 """222327@implements_to_string24class 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 """2829 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)4647 def __str__(self):
8 unmodified lines
5657 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 ]6465 # 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 )7273 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 lines
101 request.files.__class__ = newcls102103104def _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}"119120121def 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.blueprint129130 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)137141 info.append("% 5d: trying loader of %s" % (idx + 1, src_info))138 info.append(f"{idx + 1:5}: trying loader of {src_info}")139140 for line in _dump_loader_info(loader):144 info.append(" %s" % line)141 info.append(f" {line}")142143 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}")149150 seems_fishy = False151 if total_found == 0:152 info.append("Error: the template could not be found.")
3 unmodified lines
156 seems_fishy = True157158 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 lines
169def 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 lines
modified:src/flask/helpers.py+57 added-91 removed
1# -*- coding: utf-8 -*-1"""2 flask.helpers3 ~~~~~~~~~~~~~4
23 unmodified lines
28from werkzeug.routing import BuildError29from werkzeug.urls import url_quote30from werkzeug.wsgi import wrap_file3133from ._compat import fspath34from ._compat import PY235from ._compat import string_types36from ._compat import text_type32from .globals import _app_ctx_stack33from .globals import _request_ctx_stack34from .globals import current_app35from .globals import request
117 unmodified lines
153 # 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 lines
310 blueprint_name = request.blueprint311312 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:]317318 external = values.pop("_external", False)
44 unmodified lines
363 values["_scheme"] = scheme364 return appctx.app.handle_url_build_error(error, endpoint, values)365366 if anchor is not None:373 rv += "#" + url_quote(anchor)367 rv += f"#{url_quote(anchor)}"368 return rv369370371def get_template_attribute(template_name, attribute):
197 unmodified lines
569 mtime = None570 fsize = None571572 if hasattr(filename_or_fp, "__fspath__"):579 filename_or_fp = fspath(filename_or_fp)573 filename_or_fp = os.fspath(filename_or_fp)574581 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 = None
21 unmodified lines
601 if as_attachment:602 if attachment_filename is None:603 raise TypeError("filename unavailable, required for sending as attachment")604611 if not isinstance(attachment_filename, text_type):605 if not isinstance(attachment_filename, str):606 attachment_filename = attachment_filename.decode("utf-8")607608 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 lines
632 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.")639640 data = wrap_file(request.environ, file)
20 unmodified lines
661 if add_etags and filename is not None:662 from warnings import warn663664 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 )680681 if conditional:
73 unmodified lines
755 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 lines
789 # current working directory.790 if loader is None or import_name == "__main__":791 return os.getcwd()792806 # 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 lines
802 # 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 )813814 # 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 lines
818def _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 )838839840def _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.util843867 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)865866 # 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 .zip
8 unmodified lines
884 filename = sys.modules[root_mod_name].__file__885 package_path = os.path.abspath(os.path.dirname(filename))886887 # 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)892893 return package_path
26 unmodified lines
920 return base_dir, package_path921 return None, package_path922923948class locked_cached_property(object):924class 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 for
17 unmodified lines
946 obj.__dict__[self.__name__] = value947 return value948949974class _PackageBoundObject(object):950class _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 lines
1003 return self._static_url_path10041005 if self.static_folder is not None:1006 basename = os.path.basename(self.static_folder)1031 return ("/" + basename).rstrip("/")1007 return f"/{basename}".rstrip("/")10081009 @static_url_path.setter1010 def static_url_path(self, value):1011 if value is not None:
103 unmodified lines
11151116def is_ip(value):1117 """Determine if the given string is an IP address.11181143 Python 2 on Windows doesn't provide ``inet_pton``, so this only1144 checks IPv4 addresses in that environment.11451119 :param value: value to check1120 :type value: str11211122 :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 False11581125 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 line
modified:src/flask/logging.py-32 removed
1# -*- coding: utf-8 -*-1"""2flask.logging3~~~~~~~~~~~~~45:copyright: 2010 Pallets6:license: BSD-3-Clause7"""9from __future__ import absolute_import108import logging9import sys13import warnings1011from werkzeug.local import LocalProxy1213from .globals import request
38 unmodified lines
52 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")53)545560def _has_config(logger):61 """Decide if a logger has direct configuration applied by checking62 its properties against the defaults.6364 :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 )727356def create_logger(app):57 """Get the Flask app's logger and configure it if needed.5859 The logger name will be the same as
7 unmodified lines
67 :func:`~flask.logging.wsgi_errors_stream` with a basic format.68 """69 logger = logging.getLogger(app.name)7089 # 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)9394 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 break10271 if app.debug and not logger.level:72 logger.setLevel(logging.DEBUG)7374 if not has_level_handler(logger):
3 unmodified lines
modified:src/flask/sessions.py+14 added-15 removed
1# -*- coding: utf-8 -*-1"""2 flask.sessions3 ~~~~~~~~~~~~~~4
3 unmodified lines
8 :license: BSD-3-Clause9"""10import hashlib11import warnings12from collections.abc import MutableMapping13from datetime import datetime1415from itsdangerous import BadSignature16from itsdangerous import URLSafeTimedSerializer17from werkzeug.datastructures import CallbackDict1819from ._compat import collections_abc19from .helpers import is_ip20from .helpers import total_seconds21from .json.tag import TaggedJSONSerializer222325class SessionMixin(collections_abc.MutableMapping):24class SessionMixin(MutableMapping):25 """Expands a basic dictionary with session attributes."""2627 @property28 def permanent(self):
46 unmodified lines
75 def on_update(self):76 self.modified = True77 self.accessed = True7880 super(SecureCookieSession, self).__init__(initial, on_update)79 super().__init__(initial, on_update)8081 def __getitem__(self, key):82 self.accessed = True84 return super(SecureCookieSession, self).__getitem__(key)83 return super().__getitem__(key)8485 def get(self, key, default=None):86 self.accessed = True88 return super(SecureCookieSession, self).get(key, default)87 return super().get(key, default)8889 def setdefault(self, key, default=None):90 self.accessed = True92 return super(SecureCookieSession, self).setdefault(key, default)91 return super().setdefault(key, default)929394class NullSession(SecureCookieSession):95 """Class used to generate nicer error messages if sessions are not
11 unmodified lines
107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109110112class SessionInterface(object):111class 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 have
91 unmodified lines
207 # remove any leading '.' since we'll add that later208 rv = rv.rsplit(":", 1)[0].lstrip(".")209210 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 lines
231232 # 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}"236237 app.config["SESSION_COOKIE_DOMAIN"] = rv238 return rv239
154 unmodified lines
modified:src/flask/signals.py+2 added-3 removed
1# -*- coding: utf-8 -*-1"""2 flask.signals3 ~~~~~~~~~~~~~4
9 unmodified lines
14 signals_available = True15except ImportError:16 signals_available = False1719 class Namespace(object):18 class Namespace:19 def signal(self, name, doc=None):20 return _FakeSignal(name, doc)2123 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 lines
modified:src/flask/templating.py-1 removed
1# -*- coding: utf-8 -*-1"""2 flask.templating3 ~~~~~~~~~~~~~~~~4
150 unmodified lines
modified:src/flask/testing.py+10 added-30 removed
1# -*- coding: utf-8 -*-1"""2 flask.testing3 ~~~~~~~~~~~~~4
2 unmodified lines
78 :copyright: 2010 Pallets9 :license: BSD-3-Clause10"""12import warnings11from contextlib import contextmanager1213import werkzeug.test14from click.testing import CliRunner
34 unmodified lines
49 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 lines
62 http_host = app.config.get("SERVER_NAME") or "localhost"63 app_root = app.config["APPLICATION_ROOT"]6465 if subdomain:68 http_host = "{0}.{1}".format(subdomain, http_host)66 http_host = f"{subdomain}.{http_host}"6768 if url_scheme is None:69 url_scheme = app.config["PREFERRED_URL_SCHEME"]7071 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.path7778 if url.query:79 sep = b"?" if isinstance(url.query, bytes) else "?"80 path += sep + url.query8182 self.app = app86 super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)83 super().__init__(path, base_url, *args, **kwargs)8485 def json_dumps(self, obj, **kwargs):86 """Serialize ``obj`` to a JSON-formatted string.87
3 unmodified lines
91 kwargs.setdefault("app", self.app)92 return json_dumps(obj, **kwargs)939498def make_test_environ_builder(*args, **kwargs):99 """Create a :class:`flask.testing.EnvironBuilder`.100101 .. 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)11311495class 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 general
10 unmodified lines
109110 preserve_context = False111112 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 }118119 @contextmanager120 def session_transaction(self, *args, **kwargs):
115 unmodified lines
236 """237238 def __init__(self, app, **kwargs):239 self.app = app260 super(FlaskCliRunner, self).__init__(**kwargs)240 super().__init__(**kwargs)241242 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>` for
14 unmodified lines
259260 if "obj" not in kwargs:261 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)262283 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 line
67 :copyright: 2010 Pallets8 :license: BSD-3-Clause9"""11from ._compat import with_metaclass10from .globals import request111213http_method_funcs = frozenset(14 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]15)161720class View(object):18class 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 lines
25 class MyView(View):26 methods = ['GET']2728 def dispatch_request(self, name):31 return 'Hello %s!' % name29 return f"Hello {name}!"3031 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))3233 When you want to decorate a pluggable view you will have to either do that
77 unmodified lines
111 defines.112 """113114 def __init__(cls, name, bases, d):117 super(MethodViewType, cls).__init__(name, bases, d)115 super().__init__(name, bases, d)116117 if "methods" not in d:118 methods = set()119
12 unmodified lines
132 if methods:133 cls.methods = methods134135138class MethodView(with_metaclass(MethodViewType, View)):136class 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 lines
156 # retry with GET.157 if meth is None and request.method == "HEAD":158 meth = getattr(self, "get", None)159162 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 lines
20 json_module = json2122 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}")2526 raise BadRequest()2728
103 unmodified lines
132 if current_app:133 return current_app.config["MAX_COOKIE_SIZE"]134135 # return Werkzeug's default when not in an app context137 return super(Response, self).max_cookie_size136 return super().max_cookie_size
modified:tests/test_apps/cliapp/app.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask23testapp = Flask("testapp")
modified:tests/test_apps/cliapp/factory.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask234def create_app():
13 unmodified lines
modified:tests/test_apps/cliapp/importerrorapp.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask23raise ImportError()4
1 unmodified line
modified:tests/test_apps/cliapp/multiapp.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask23app1 = Flask("app1")4app2 = Flask("app2")
modified:tests/conftest.py+13 added-17 removed
1# -*- coding: utf-8 -*-1"""2 tests.conftest3 ~~~~~~~~~~~~~~4
105 unmodified lines
110 """111 if not request.param:112 return113115 class LimitedLoader(object):114 class LimitedLoader:115 def __init__(self, loader):116 self.loader = loader117118 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)122123 old_get_loader = pkgutil.get_loader124
21 unmodified lines
146def 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 rv
4 unmodified lines
159 """Generate egg from package name inside base and put the egg into160 sys.path."""161162 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()165166 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 )180181 import subprocess182183 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_path189190 return inner
8 unmodified lines
modified:tests/test_appctx.py+2 added-3 removed
1# -*- coding: utf-8 -*-1"""2 tests.appctx3 ~~~~~~~~~~~~4
156 unmodified lines
161 assert repr(flask.g) == "<flask.g of 'flask_test'>"162163164def test_custom_app_ctx_globals_class(app):166 class CustomRequestGlobals(object):165 class CustomRequestGlobals:166 def __init__(self):167 self.spam = "eggs"168169 app.app_ctx_globals_class = CustomRequestGlobals
18 unmodified lines
188 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 ""193194 res = client.get("/")195 assert res.status_code == 200196 assert res.data == b""
23 unmodified lines
modified:tests/test_basic.py+31 added-42 removed
1# -*- coding: utf-8 -*-1"""2 tests.basic3 ~~~~~~~~~~~~~~~~~~~~~4
17 unmodified lines
22from werkzeug.http import parse_date23from werkzeug.routing import BuildError2425import flask27from flask._compat import text_type262728def test_options_work(app, client):29 @app.route("/", methods=["GET", "POST"])
59 unmodified lines
89 rv = client.post("/")90 assert rv.status_code == 40591 assert sorted(rv.allow) == ["GET", "HEAD"]9295 # 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")10094 assert rv.status_code == 4059596 rv = client.head("/")97 assert rv.status_code == 200
4 unmodified lines
102 rv = client.delete("/more")103 assert rv.status_code == 405104 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]105113 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")117107 assert rv.status_code == 405108109110def test_request_dispatching(app, client):
165 unmodified lines
276 assert "httponly" in rv.headers["set-cookie"].lower()277278279def 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 lines
360361 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)365366367def test_session_ip_warning(recwarn, app, client):368 app.config.update(SERVER_NAME="127.0.0.1:5000")
32 unmodified lines
401 return ""402403 @app.route("/test")404 def test():416 return text_type(flask.session.permanent)405 return str(flask.session.permanent)406407 rv = client.get("/")408 assert "set-cookie" in rv.headers409 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])
171 unmodified lines
581 # instead of propagating exceptions.582583 @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 ""589590 @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 ""599600 @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 ""610611 @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 ""618619 @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 ""629630 @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 ""637638 # Create new test client on each test to clean flashed messages.639
454 unmodified lines
1094 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)109911001101def 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"11051106 @app.route("/bytes")1107 def from_bytes():1119 return u"Hällo Wörld".encode("utf-8")1108 return "Hällo Wörld".encode()11091110 @app.route("/full_tuple")1111 def from_full_tuple():1112 return (
28 unmodified lines
1141 @app.route("/dict")1142 def from_dict():1143 return {"foo": "bar"}, 20111441156 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()11471148 rv = client.get("/full_tuple")1149 assert rv.data == b"Meh"1150 assert rv.headers["X-Foo"] == "Testing"
458 unmodified lines
1609 assert url == expected161016111612def test_nonascii_pathinfo(app, client):1624 @app.route(u"/киртест")1613 @app.route("/киртест")1614 def index():1615 return "Hello World!"16161628 rv = client.get(u"/киртест")1617 rv = client.get("/киртест")1618 assert rv.data == b"Hello World!"161916201621def test_debug_mode_complains_after_first_request(app, client):
198 unmodified lines
1820 app.config["SERVER_NAME"] = "localhost.localdomain"18211822 @app.route("/", subdomain="<user>")1823 def index(user):1835 return "index for %s" % user1824 return f"index for {user}"18251826 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1827 assert rv.data == b"index for mitsuhiko"1828
4 unmodified lines
1833 client = app.test_client()18341835 @app.route("/", subdomain="<user>")1836 def index(user):1848 return "index for %s" % user1837 return f"index for {user}"18381839 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1840 assert rv.data == b"index for mitsuhiko"1841
31 unmodified lines
1873 assert rv.data == b"b"187418751876def 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 lines
1905 rv = {}19061907 # 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} ..."19101911 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} ..."191519161917@pytest.mark.parametrize(1918 "host,port,server_name,expect_host,expect_port",
50 unmodified lines
modified:tests/test_blueprints.py+2 added-4 removed
1# -*- coding: utf-8 -*-1"""2 tests.blueprints3 ~~~~~~~~~~~~~~~~4
8 unmodified lines
13from jinja2 import TemplateNotFound14from werkzeug.http import parse_cache_control_header1516import flask18from flask._compat import text_type171819def test_blueprint_specific_error_handling(app, client):20 frontend = flask.Blueprint("frontend", __name__)
122 unmodified lines
143 bp = flask.Blueprint("test", __name__)144145 @bp.route("/foo", defaults={"baz": 42})146 def foo(bar, baz):149 return "%s/%d" % (bar, baz)147 return f"{bar}/{baz:d}"148149 @bp.route("/bar")150 def bar(bar):153 return text_type(bar)151 return str(bar)152153 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 lines
modified:tests/test_cli.py+10 added-18 removed
1# -*- coding: utf-8 -*-1"""2 tests.test_cli3 ~~~~~~~~~~~~~~4
1 unmodified line
6 :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.11from __future__ import absolute_import1210import os11import ssl12import sys13import types
243 unmodified lines
257 from flask import __version__ as flask_version258 from werkzeug import __version__ as werkzeug_version259 from platform import python_version260264 class MockCtx(object):261 class MockCtx:262 resilient_parsing = False263 color = None264265 def exit(self):
1 unmodified line
267268 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 out274275276def test_scriptinfo(test_apps, monkeypatch):277 """Test of ScriptInfo."""
9 unmodified lines
287 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 lines
405 click.echo(str(current_app.debug))406407 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"410411412def test_print_exceptions(runner):413 """Print the stacktrace if the CLI."""
171 unmodified lines
585 # ImportError586 with pytest.raises(click.BadParameter):587 run_command.make_context("run", ["--cert", "not_here"])588592 # 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"])591592 # 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)594595 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_context
57 unmodified lines
655 bp = Blueprint("blue", __name__, cli_group="blue")656 app.register_blueprint(bp)657658 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 lines
1213import pytest1415import flask17from flask._compat import PY2161718# config keys used for the TestConfig19TEST_KEY = "foo"
7 unmodified lines
272829def 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)333435def test_config_from_object():
27 unmodified lines
63 app.config.from_mapping({}, {})646566def test_config_from_class():69 class Base(object):67 class Base:68 TEST_KEY = "foo"6970 class Test(Base):71 SECRET_KEY = "config"
11 unmodified lines
83 assert "'FOO_SETTINGS' is not set" in str(e.value)84 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)8586 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 lines
184def 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 lines
9 def to_python(self, value):10 return value.split(",")1112 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)1516 app.url_map.converters["list"] = ListConverter17
23 unmodified lines
deleted:tests/test_deprecations.py-12 removed
1import pytest23from flask import json_available456def 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 E7121112 assert len(rec.list) == 3
modified:tests/test_helpers.py+36 added-48 removed
1# -*- coding: utf-8 -*-1"""2 tests.helpers3 ~~~~~~~~~~~~~~~~~~~~~~~4
17 unmodified lines
22from werkzeug.http import parse_options_header2324import flask25from flask import json27from flask._compat import PY228from flask._compat import StringIO29from flask._compat import text_type26from flask.helpers import get_debug_flag27from flask.helpers import get_env2829
6 unmodified lines
36 except LookupError:37 return False383944class FakePath(object):40class FakePath:41 """Fake object to represent a ``PathLike object``.4243 This represents a ``pathlib.Path`` object in python 3.44 See: https://www.python.org/dev/peps/pep-0519/
26 unmodified lines
71 def dst(self, dt):72 return datetime.timedelta()737479class TestJSON(object):75class 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 lines
90 ),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) == value9596 @pytest.mark.parametrize("debug", (True, False))97 def test_bad_request_debug_message(self, app, client, debug):
12 unmodified lines
110111 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()))115116 rv = client.post("/json", data="malformed", content_type="application/json")117 assert rv.status_code == 400118
5 unmodified lines
124 rv = client.post("/json", data='"foo"', content_type="application/x+json")125 assert rv.data == b"foo"126127 @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):131132 app.config["JSON_AS_ASCII"] = test_value138 rv = flask.json.dumps(u"\N{SNOWMAN}")133 rv = flask.json.dumps("\N{SNOWMAN}")134 assert rv == expected135136 def test_json_dump_to_file(self, app, app_ctx):137 test_data = {"name": "Flask"}143 out = StringIO()138 out = io.StringIO()139140 flask.json.dump(test_data, out)141 out.seek(0)142 rv = flask.json.load(out)
72 unmodified lines
215 datetime.date(1975, 1, 5),216 )217218 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 lines
248 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"])253254 rv = client.post(255 "/add",256 data=flask.json.dumps({"a": 1, "b": 2}),
3 unmodified lines
260261 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 lines
278 )279 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'280281 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 = val285286 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)291292 class MyDecoder(flask.json.JSONDecoder):293 def __init__(self, *args, **kwargs):
19 unmodified lines
313 )314 assert rv.data == b'"<42>"'315316 def test_blueprint_json_customization(self, app, client):322 class X(object): # noqa: B903, for Python2 compatibility317 class X:318 __slots__ = ("val",)319320 def __init__(self, val):321 self.val = val322323 class MyEncoder(flask.json.JSONEncoder):324 def default(self, o):325 if isinstance(o, X):329 return "<%d>" % o.val326 return f"<{o.val}>"327328 return flask.json.JSONEncoder.default(self, o)329330 class MyDecoder(flask.json.JSONDecoder):
37 unmodified lines
368 @app.route("/")369 def index():370 return flask.request.args["foo"]371375 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()375376 def test_json_key_sorting(self, app, client):377 app.debug = True378
64 unmodified lines
443 except AssertionError:444 assert lines == sorted_by_str445446450class PyStringIO(object):447class PyBytesIO:448 def __init__(self, *args, **kwargs):449 self._io = io.BytesIO(*args, **kwargs)450451 def __getattr__(self, name):452 return getattr(self._io, name)453454458class TestSendfile(object):455class 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 lines
499 "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 lines
516517 @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 lines
673 ("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_disposition697698 def test_static_file(self, app, req_ctx):
76 unmodified lines
775 with pytest.raises(exception):776 flask.send_from_directory("static", "bad\x00")777778791class TestUrlFor(object):779class TestUrlFor:780 def test_url_for_with_anchor(self, app, req_ctx):781 @app.route("/")782 def index():783 return "42"
35 unmodified lines
819 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}"824825 def post(self):826 return "Create"827
6 unmodified lines
834 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"835 assert flask.url_for("myview", _method="POST") == "/myview/create"836837850class TestNoImports(object):838class TestNoImports:839 """Test Flasks are created without import.840841 Avoiding ``__import__`` helps create Flask instances where there are errors842 at import time. Those runtime errors will be apparent to the user soon
10 unmodified lines
853 except NotImplementedError:854 AssertionError("Flask(import_name) is importing import_name.")855856869class TestStreaming(object):857class TestStreaming:858 def test_streaming_with_context(self, app, client):859 @app.route("/")860 def index():861 def generate():
22 unmodified lines
884885 def test_streaming_with_context_and_custom_close(self, app, client):886 called = []887900 class Wrapper(object):888 class Wrapper:889 def __init__(self, gen):890 self._gen = gen891892 def __iter__(self):
34 unmodified lines
927 rv = client.get("/")928 assert rv.data == b"flask"929930943class TestSafeJoin(object):931class 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 lines
968 with pytest.raises(NotFound):969 print(flask.safe_join(*args))970971984class TestHelpers(object):972class TestHelpers:973 @pytest.mark.parametrize(974 "debug, expected_flag, expected_default_flag",975 [976 ("", False, False),
55 unmodified lines
modified:tests/test_instance_config.py+3 added-19 removed
1# -*- coding: utf-8 -*-1"""2 tests.test_instance3 ~~~~~~~~~~~~~~~~~~~4
5 unmodified lines
1011import pytest1213import flask15from flask._compat import PY2141516def test_explicit_instance_paths(modules_tmpdir):17 with pytest.raises(ValueError) as excinfo:
3 unmodified lines
21 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))22 assert app.instance_path == str(modules_tmpdir)232427@pytest.mark.xfail(reason="TODO: weird interaction with tox")25@pytest.mark.xfail(reason="weird interaction with tox")26def 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 lines
33 here = os.path.abspath(os.getcwd())34 assert app.instance_path == os.path.join(here, "instance")353637@pytest.mark.xfail(reason="weird interaction with tox")38def 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 lines
4849 assert app.instance_path == str(modules_tmpdir.join("instance"))505152@pytest.mark.xfail(reason="weird interaction with tox")53def 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 lines
125 )126 finally:127 if "site_egg" in sys.modules:128 del sys.modules["site_egg"]129130131@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")132def 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__)")135136 class Loader(object):137 def find_module(self, name, path=None):138 return self139140 sys.meta_path.append(Loader())141 request.addfinalizer(sys.meta_path.pop)142143 with pytest.raises(AttributeError):144 import unimportable # noqa: F401
modified:tests/test_json_tag.py+1 added-2 removed
1# -*- coding: utf-8 -*-1"""2tests.test_json_tag3~~~~~~~~~~~~~~~~~~~4
41 unmodified lines
46 assert isinstance(s.order[0], TagDict)474849def 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 = data5354 class TagFoo(JSONTag):
38 unmodified lines
modified:tests/test_logging.py+1 added-11 removed
1# -*- coding: utf-8 -*-1"""2tests.test_logging3~~~~~~~~~~~~~~~~~~~4
1 unmodified line
6:license: BSD-3-Clause7"""8import logging9import sys10from io import StringIO1112import pytest1314from flask._compat import StringIO14from flask.logging import default_handler15from flask.logging import has_level_handler16from flask.logging import wsgi_errors_stream17
84 unmodified lines
102 assert rv.data103 err = stream.getvalue()104 assert "Exception on / [GET]" in err105 assert "Exception: test" in err107108109def 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))113114 with pytest.warns(UserWarning):115 assert app.logger.getEffectiveLevel() == logging.WARNING
deleted:tests/test_meta.py-6 removed
1import io234def 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 lines
7 :copyright: 2010 Pallets8 :license: BSD-3-Clause9"""10import gc12import sys11import platform12import threading1314import pytest15from werkzeug.exceptions import NotFound
2 unmodified lines
1819_gc_lock = threading.Lock()202123class assert_no_leak(object):22class assert_no_leak:23 def __enter__(self):24 gc.disable()25 _gc_lock.acquire()26 loc = flask._request_ctx_stack._local
15 unmodified lines
42 _gc_lock.release()43 gc.enable()444546@pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="CPython only")47def test_memory_consumption():48 app = flask.Flask(__name__)4950 @app.route("/")
8 unmodified lines
5960 # Trigger caches61 fire()6263 # 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()666768def test_safe_join_toplevel_pardir():69 from flask.helpers import safe_join
26 unmodified lines
modified:tests/test_reqctx.py+6 added-15 removed
1# -*- coding: utf-8 -*-1"""2 tests.reqctx3 ~~~~~~~~~~~~4
104 unmodified lines
109110def 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']}!"114115 @app.route("/meh")116 def meh():117 return flask.request.url
19 unmodified lines
137138def 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']}!"142143 ctx = app.test_request_context("/?name=World")144 ctx.push()145 assert index() == "Hello World!"
2 unmodified lines
148 index()149150151@pytest.mark.skipif(greenlet is None, reason="greenlet not installed")153class TestGreenletContextCopying(object):152class TestGreenletContextCopying:153 def test_greenlet_context_copying(self, app, client):154 greenlets = []155156 @app.route("/")
80 unmodified lines
237 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)242243 class CustomFlask(flask.Flask):244 session_interface = PathAwareSessionInterface()245
37 unmodified lines
283284def test_bad_environ_raises_bad_request():285 app = flask.Flask(__name__)286288 # 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.291287 from flask.testing import EnvironBuilder288289 builder = EnvironBuilder(app)290 environ = builder.get_environ()291292 # use a non-printable character in the Host - this is key to this test298 environ["HTTP_HOST"] = u"\x8a"293 environ["HTTP_HOST"] = "\x8a"294295 with app.request_context(environ):296 response = app.full_dispatch_request()297 assert response.status_code == 400
5 unmodified lines
303 @app.route("/")304 def index():305 return "Hello World!"306312 # 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.315307 from flask.testing import EnvironBuilder308309 builder = EnvironBuilder(app)310 environ = builder.get_environ()311312 # these characters are all IDNA-compatible322 environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"313 environ["HTTP_HOST"] = "ąśźäüжŠßя.com"314315 with app.request_context(environ):316 response = app.full_dispatch_request()317
12 unmodified lines
modified:tests/test_signals.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.signals3 ~~~~~~~~~~~~~~~~~~~~~~~4
201 unmodified lines
modified:tests/test_subclassing.py+2 added-2 removed
1# -*- coding: utf-8 -*-1"""2 tests.subclassing3 ~~~~~~~~~~~~~~~~~4
2 unmodified lines
78 :copyright: 2010 Pallets9 :license: BSD-3-Clause10"""11from io import StringIO1213import flask13from flask._compat import StringIO141516def test_suppressed_exception_logging():17 class SuppressedFlask(flask.Flask):
14 unmodified lines
modified:tests/test_templating.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2 tests.templating3 ~~~~~~~~~~~~~~~~4
408 unmodified lines
413 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 text429430 with app.test_client() as c:
22 unmodified lines
modified:tests/test_testing.py+9 added-23 removed
1# -*- coding: utf-8 -*-1"""2 tests.testing3 ~~~~~~~~~~~~~4
7 unmodified lines
12import werkzeug1314import flask15from flask import appcontext_popped17from flask._compat import text_type16from flask.cli import ScriptInfo17from flask.json import jsonify18from flask.testing import EnvironBuilder19from flask.testing import FlaskCliRunner22from flask.testing import make_test_environ_builder2021try:22 import blinker23except ImportError:
34 unmodified lines
58 return flask.request.remote_addr5960 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__}"636465def test_environ_base_modified(app, client, app_ctx):66 @app.route("/")
50 unmodified lines
117 assert eb.script_root == ""118 assert eb.path == "/"119120124def 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 == "/"131132121def 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"'126127128def test_blueprint_with_subdomain():129 app = flask.Flask(__name__, subdomain_matching=True)
37 unmodified lines
167168 rv = client.get("/")169 assert rv.data == b"index"170 assert flask.session.get("data") == "foo"171172 rv = client.post("/", data={}, follow_redirects=True)173 assert rv.data == b"foo"174 assert flask.session.get("data") == "foo"175186 # This support requires a new Werkzeug version187 if not hasattr(client, "redirect_client"):188 assert flask.session.get("data") == "foo"189176 rv = client.get("/getsession")177 assert rv.data == b"foo"178179180def test_session_transactions(app, client):181 @app.route("/")182 def index():197 return text_type(flask.session["foo"])183 return str(flask.session["foo"])184185 with client:186 with client.session_transaction() as sess:187 assert len(sess) == 0
132 unmodified lines
320@pytest.mark.skipif(blinker is None, reason="blinker is not installed")321def 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']}!"325340 class Namespace(object):326 class Namespace:327 count = 0328329 def add(self, app):330 self.count += 1
69 unmodified lines
400 assert "Hello" in result.output401402403def test_cli_custom_obj(app):418 class NS(object):404 class NS:405 called = False406407 def create_app():408 NS.called = True
25 unmodified lines
modified:tests/test_user_error_handler.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2tests.test_user_error_handler3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~4
23 unmodified lines
28 assert isinstance(e, InternalServerError)29 original = getattr(e, "original_exception", None)3031 if original is not None:33 return "wrapped " + type(original).__name__32 return f"wrapped {type(original).__name__}"3334 return "direct"3536 @app.route("/custom")
169 unmodified lines
206 # Don't handle RequestRedirect raised when adding slash.207 assert c.get("/slash", follow_redirects=True).data == b"slash"208209211class TestGenericHandlers(object):210class TestGenericHandlers:211 """Test how very generic handlers are dispatched to."""212213 class Custom(Exception):214 pass
22 unmodified lines
237 def report_error(self, e):238 original = getattr(e, "original_exception", None)239240 if original is not None:242 return "wrapped " + type(original).__name__241 return f"wrapped {type(original).__name__}"242244 return "direct " + type(e).__name__243 return f"direct {type(e).__name__}"244245 @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 should
41 unmodified lines
modified:tests/test_views.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.views3 ~~~~~~~~~~~4
247 unmodified lines
modified:.azure-pipelines.yml+36 added-77 removed
1trigger:2 - 'master'2 - master3 - '*.x'45jobs:6 - job: Tests7 variables:8 vmImage: 'ubuntu-latest'9 python.version: '3.8'10 TOXENV: 'py,coverage-ci'5variables:6 vmImage: ubuntu-latest7 python.version: '3.8'8 TOXENV: py11 hasTestResults: 'true'913 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'10strategy: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: style3043 pool:44 vmImage: $[ variables.vmImage ]31pool:32 vmImage: $[ variables.vmImage ]3346 steps:47 - task: UsePythonVersion@048 inputs:49 versionSpec: $(python.version)50 displayName: Use Python $(python.version)34steps:35 - task: UsePythonVersion@036 inputs:37 versionSpec: $(python.version)38 displayName: Use Python $(python.version)3952 - script: pip --disable-pip-version-check install -U tox53 displayName: Install tox40 - script: pip --disable-pip-version-check install -U tox41 displayName: Install tox4255 - script: tox -s false -- --junitxml=test-results.xml tests examples56 displayName: Run tox5758 - task: PublishTestResults@259 inputs:60 testResultsFiles: test-results.xml61 testRunTitle: $(Agent.JobName)62 condition: eq(variables['hasTestResults'], 'true')63 displayName: Publish test results6465 - task: PublishCodeCoverageResults@166 inputs:67 codeCoverageTool: Cobertura68 summaryFileLocation: coverage.xml69 condition: eq(variables['hasTestResults'], 'true')70 displayName: Publish coverage results7172 # 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 tox8384 - script: tox -e nightly85 displayName: Run tox43 - script: tox44 displayName: Run tox
modified:.pre-commit-config.yaml+13 added-6 removed
1repos: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-fixer
modified:CHANGES.rst+8 added-10 removed
1.. currentmodule:: flask23Version 1.2.03Version 2.0.04-------------56Unreleased78- 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 lines
452Released 2016-05-29, codename Absinthe453454- 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 lines
567568Released 2013-06-13, codename Limoncello569570- 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 lines
596 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 lines
760 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 lines
840- 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 lines
857 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.862863864Version 0.6.1865-------------
171 unmodified lines
modified:CONTRIBUTING.rst+3 added-2 removed
133 unmodified lines
134depends on which part of Flask you're working on. Travis-CI will run the full135suite when you submit your pull request.136137The full test suite takes a long time to run because it tests multiple138combinations of Python and dependencies. You need to have Python 2.7, 3.4,1393.5, 3.6, 3.7 and PyPy 2.7 installed to run all of the environments. Then run::138combinations of Python and dependencies. If you don't have a Python139version installed, it will be skipped with a warning message at the end.140Run::141142 tox143144Running test coverage
53 unmodified lines
modified:setup.cfg+8 added-10 removed
1[bdist_wheel]2universal = true31[tool:pytest]2testpaths = tests3filterwarnings =4 error56[coverage:run]7branch = True8source =
1 unmodified line
10 tests1112[coverage:paths]13source =15 src/flask16 .tox/*/lib/python*/site-packages/flask17 .tox/*/site-packages/flask14 src15 */site-packages1617[flake8]18# B = bugbear19# E = pycodestyle errors20# F = flake8 pyflakes21# W = pycodestyle warnings22# B9 = bugbear opinions23# ISC = implicit-str-concat25select = B, E, F, W, B924select = B, E, F, W, B9, ISC25ignore =26 # slice notation whitespace, invalid27 E20328 # import at top, too many circular import fixes
6 unmodified lines
35 W50336# up to 88 allowed by bugbear B95037max-line-length = 8038per-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: F401
modified:setup.py+3 added-13 removed
1import io1import re23from setuptools import find_packages4from setuptools import setup57with io.open("README.rst", "rt", encoding="utf8") as f:6with open("README.rst", encoding="utf8") as f:7 readme = f.read()810with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f:9with open("src/flask/__init__.py", encoding="utf8") as f:10 version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)1112setup(13 name="Flask",
18 unmodified lines
32 "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 lines
modified:tox.ini+4 added-31 removed
1[tox]2envlist =3 py{38,37,36,35,27,py3,py}3 py{38,37,36,py3}4 py38-{simplejson,devel,lowest}5 style6 docs6 coverage7skip_missing_interpreters = true89[testenv]10passenv = LANG10deps =11 pytest13 coverage12 greenlet13 blinker14 python-dotenv15
10 unmodified lines
2627 simplejson: simplejson2829commands =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]3236 # 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}3439[testenv:nightly]40# courtesy Python nightly test, don't fail the build in CI41ignore_outcome = true42commands =43 coverage run -p -m pytest --tb=short -Werror --junitxml=test-results.xml tests4435[testenv:style]36deps = pre-commit37skip_install = true38commands = pre-commit run --all-files --show-diff-on-failure3940[testenv:docs]51deps =52 -r docs/requirements.txt41deps = -r docs/requirements.txt42commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html5455[testenv:coverage]56deps = coverage57skip_install = true58commands =59 coverage combine60 coverage html61 coverage report6263[testenv:coverage-ci]64deps = coverage65skip_install = true66commands =67 coverage combine68 coverage xml69 coverage report