Skip to content
Myr

Merge remote-tracking branch 'origin/2.0.x'

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

authored by David Lord · committed by David Lord · parents 0826be4, ef3a82a · Browse files · 17 files+138 added−78 removed
This commit

State

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

Diff stats

17 files+138 added−78 removed

  • tests:+34 added−1 removed
  • other:+104 added−77 removed

17 files+138 added−78 removed

modified:docs/deploying/asgi.rst+2 added-2 removed
3 unmodified lines
4====56If you'd like to use an ASGI server you will need to utilise WSGI to7ASGI middleware. The asgiref8[WsgiToAsgi](https://github.com/django/asgiref#wsgi-to-asgi-adapter)8`WsgiToAsgi <https://github.com/django/asgiref#wsgi-to-asgi-adapter>`_9adapter is recommended as it integrates with the event loop used for10Flask's :ref:`async_await` support. You can use the adapter by11wrapping the Flask app,12
7 unmodified lines
20 ...2122 asgi_app = WsgiToAsgi(app)2324and then serving the ``asgi_app`` with the asgi server, e.g. using24and then serving the ``asgi_app`` with the ASGI server, e.g. using25`Hypercorn <https://gitlab.com/pgjones/hypercorn>`_,2627.. sourcecode:: text28
1 unmodified line
modified:docs/patterns/jquery.rst+3 added-4 removed
21 unmodified lines
22to add a script statement to the bottom of your ``<body>`` to load jQuery:2324.. sourcecode:: html2526 <script type=text/javascript src="{{27 url_for('static', filename='jquery.js') }}"></script>26 <script src="{{ url_for('static', filename='jquery.js') }}"></script>2728Another method is using Google's `AJAX Libraries API29<https://developers.google.com/speed/libraries/>`_ to load jQuery:30
26 unmodified lines
57like this:5859.. sourcecode:: html+jinja6062 <script type=text/javascript>61 <script>62 $SCRIPT_ROOT = {{ request.script_root|tojson }};63 </script>6465
41 unmodified lines
107usually a better idea to have that in a separate script file:108109.. sourcecode:: html110112 <script type=text/javascript>111 <script>112 $(function() {113 $('a#calculate').bind('click', function() {114 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {115 a: $('input[name="a"]').val(),
33 unmodified lines
modified:docs/tutorial/tests.rst+1 added-1 removed
268 unmodified lines
269 assert 'http://localhost/auth/login' == response.headers['Location']270271 with app.app_context():272 assert get_db().execute(273 "select * from user where username = 'a'",273 "SELECT * FROM user WHERE username = 'a'",274 ).fetchone() is not None275276277 @pytest.mark.parametrize(('username', 'password', 'message'), (
284 unmodified lines
modified:docs/tutorial/views.rst+32 added-28 removed
89 unmodified lines
90 if not username:91 error = 'Username is required.'92 elif not password:93 error = 'Password is required.'94 elif db.execute(95 'SELECT id FROM user WHERE username = ?', (username,)96 ).fetchone() is not None:97 error = f"User {username} is already registered."9495 if error is None:96 try:100 db.execute(101 'INSERT INTO user (username, password) VALUES (?, ?)',102 (username, generate_password_hash(password))103 )104 db.commit()105 return redirect(url_for('auth.login'))97 db.execute(98 "INSERT INTO user (username, password) VALUES (?, ?)",99 (username, generate_password_hash(password)),100 )101 db.commit()102 except db.IntegrityError:103 error = f"User {username} is already registered."104 else:105 return redirect(url_for("auth.login"))106107 flash(error)108109 return render_template('auth/register.html')
14 unmodified lines
124 input their ``username`` and ``password``.125126#. Validate that ``username`` and ``password`` are not empty.127128#. Validate that ``username`` is not already registered by querying the129 database and checking if a result is returned.130 :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL query131 with ``?`` placeholders for any user input, and a tuple of values132 to replace the placeholders with. The database library will take133 care of escaping the values so you are not vulnerable to a134 *SQL injection attack*.128#. If validation succeeds, insert the new user data into the database.129136 :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.137 If the query returned no results, it returns ``None``. Later,138 :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of139 all results.130 - :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL131 query with ``?`` placeholders for any user input, and a tuple of132 values to replace the placeholders with. The database library133 will take care of escaping the values so you are not vulnerable134 to a *SQL injection attack*.135141#. If validation succeeds, insert the new user data into the database.142 For security, passwords should never be stored in the database143 directly. Instead,144 :func:`~werkzeug.security.generate_password_hash` is used to145 securely hash the password, and that hash is stored. Since this146 query modifies data, :meth:`db.commit() <sqlite3.Connection.commit>`147 needs to be called afterwards to save the changes.136 - For security, passwords should never be stored in the database137 directly. Instead,138 :func:`~werkzeug.security.generate_password_hash` is used to139 securely hash the password, and that hash is stored. Since this140 query modifies data,141 :meth:`db.commit() <sqlite3.Connection.commit>` needs to be142 called afterwards to save the changes.143144 - An :exc:`sqlite3.IntegrityError` will occur if the username145 already exists, which should be shown to the user as another146 validation error.147148#. After storing the user, they are redirected to the login page.149 :func:`url_for` generates the URL for the login view based on its150 name. This is preferable to writing the URL directly as it allows151 you to change the URL later without changing all code that links to
46 unmodified lines
198There are a few differences from the ``register`` view:199200#. The user is queried first and stored in a variable for later use.201202 :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.203 If the query returned no results, it returns ``None``. Later,204 :meth:`~sqlite3.Cursor.fetchall` will be used, which returns a list205 of all results.206207#. :func:`~werkzeug.security.check_password_hash` hashes the submitted208 password in the same way as the stored hash and securely compares209 them. If they match, the password is valid.210
95 unmodified lines
modified:docs/api.rst+1 added-1 removed
254 unmodified lines
255the filter to render data inside ``<script>`` tags.256257.. sourcecode:: html+jinja258259 <script type=text/javascript>259 <script>260 const names = {{ names|tosjon }};261 renderChart(names, {{ axis_data|tojson }});262 </script>263
512 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
624 unmodified lines
625 @app.route('/upload', methods=['GET', 'POST'])626 def upload_file():627 if request.method == 'POST':628 file = request.files['the_file']629 file.save(f"/var/www/uploads/{secure_filename(f.filename)}")629 file.save(f"/var/www/uploads/{secure_filename(file.filename)}")630 ...631632For some better examples, see :doc:`patterns/fileuploads`.633
305 unmodified lines
modified:examples/tutorial/flaskr/auth.py+13 added-13 removed
58 unmodified lines
59 if not username:60 error = "Username is required."61 elif not password:62 error = "Password is required."63 elif (64 db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()65 is not None66 ):67 error = f"User {username} is already registered."6364 if error is None:70 # the name is available, store it in the database and go to71 # the login page72 db.execute(73 "INSERT INTO user (username, password) VALUES (?, ?)",74 (username, generate_password_hash(password)),75 )76 db.commit()77 return redirect(url_for("auth.login"))65 try:66 db.execute(67 "INSERT INTO user (username, password) VALUES (?, ?)",68 (username, generate_password_hash(password)),69 )70 db.commit()71 except db.IntegrityError:72 # The username was already taken, which caused the73 # commit to fail. Show a validation error.74 error = f"User {username} is already registered."75 else:76 # Success, go to the login page.77 return redirect(url_for("auth.login"))7879 flash(error)8081 return render_template("auth/register.html")
35 unmodified lines
modified:examples/tutorial/tests/test_auth.py+1 added-1 removed
14 unmodified lines
1516 # test that the user was inserted into the database17 with app.app_context():18 assert (19 get_db().execute("select * from user where username = 'a'").fetchone()19 get_db().execute("SELECT * FROM user WHERE username = 'a'").fetchone()20 is not None21 )2223
46 unmodified lines
modified:src/flask/json/__init__.py+8 added-1 removed
1import decimal2import io3import json as _json4import typing as t5import uuid
41 unmodified lines
47 serialized, they are handled before this method.48 """49 if isinstance(o, date):50 return http_date(o)50 if isinstance(o, uuid.UUID):51 if isinstance(o, (decimal.Decimal, uuid.UUID)):52 return str(o)53 if dataclasses and dataclasses.is_dataclass(o):54 return dataclasses.asdict(o)55 if hasattr(o, "__html__"):
61 unmodified lines
117 :param app: Use this app's config instead of the active app context118 or defaults.119 :param kwargs: Extra arguments passed to :func:`json.dumps`.120121 .. versionchanged:: 2.0.2122 :class:`decimal.Decimal` is supported by converting to a string.123124 .. versionchanged:: 2.0125 ``encoding`` is deprecated and will be removed in Flask 2.1.126127 .. versionchanged:: 1.0.3
199 unmodified lines
327 The default output omits indents and spaces after separators. In328 debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,329 the output will be formatted to be easier to read.330331 .. versionchanged:: 2.0.2332 :class:`decimal.Decimal` is supported by converting to a string.333334 .. versionchanged:: 0.11335 Added support for serializing top-level arrays. This introduces336 a security risk in ancient browsers. See :ref:`security-json`.337
20 unmodified lines
modified:src/flask/app.py+1 added-1 removed
387 unmodified lines
388 def __init__(389 self,390 import_name: str,391 static_url_path: t.Optional[str] = None,392 static_folder: t.Optional[str] = "static",392 static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",393 static_host: t.Optional[str] = None,394 host_matching: bool = False,395 subdomain_matching: bool = False,396 template_folder: t.Optional[str] = "templates",
1697 unmodified lines
modified:src/flask/blueprints.py+2 added-1 removed
1import os2import typing as t3from collections import defaultdict4from functools import update_wrapper5
169 unmodified lines
175 def __init__(176 self,177 name: str,178 import_name: str,178 static_folder: t.Optional[str] = None,179 static_folder: t.Optional[t.Union[str, os.PathLike]] = None,180 static_url_path: t.Optional[str] = None,181 template_folder: t.Optional[str] = None,182 url_prefix: t.Optional[str] = None,183 subdomain: t.Optional[str] = None,
426 unmodified lines
modified:src/flask/cli.py+24 added-20 removed
101 unmodified lines
102 DeprecationWarning,103 )104 kwargs["script_info"] = script_info105106 if (107 not args108 and len(sig.parameters) == 1109 and next(iter(sig.parameters.values())).default is inspect.Parameter.empty110 ):111 warnings.warn(112 "Script info is deprecated and will not be passed as the"113 " single argument to the app factory function in Flask"114 " 2.1.",115 DeprecationWarning,116 )117 args.append(script_info)106 if not args and len(sig.parameters) == 1:107 first_parameter = next(iter(sig.parameters.values()))108109 if (110 first_parameter.default is inspect.Parameter.empty111 # **kwargs is reported as an empty default, ignore it112 and first_parameter.kind is not inspect.Parameter.VAR_KEYWORD113 ):114 warnings.warn(115 "Script info is deprecated and will not be passed as the"116 " single argument to the app factory function in Flask"117 " 2.1.",118 DeprecationWarning,119 )120 args.append(script_info)121122 return app_factory(*args, **kwargs)123124125def _called_with_wrong_args(f):
188 unmodified lines
314 def __init__(self, loader, use_eager_loading=None):315 self.loader = loader316 self._app = None317 self._lock = Lock()315 self._bg_loading_exc_info = None318 self._bg_loading_exc = None319320 if use_eager_loading is None:321 use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"322
7 unmodified lines
330 __traceback_hide__ = True # noqa: F841331 with self._lock:332 try:333 self._load_unlocked()331 except Exception:332 self._bg_loading_exc_info = sys.exc_info()334 except Exception as e:335 self._bg_loading_exc = e336337 t = Thread(target=_load_app, args=())338 t.start()339340 def _flush_bg_loading_exception(self):341 __traceback_hide__ = True # noqa: F841339 exc_info = self._bg_loading_exc_info340 if exc_info is not None:341 self._bg_loading_exc_info = None342 raise exc_info342 exc = self._bg_loading_exc343344 if exc is not None:345 self._bg_loading_exc = None346 raise exc347348 def _load_unlocked(self):349 __traceback_hide__ = True # noqa: F841350 self._app = rv = self.loader()347 self._bg_loading_exc_info = None351 self._bg_loading_exc = None352 return rv353354 def __call__(self, environ, start_response):355 __traceback_hide__ = True # noqa: F841
643 unmodified lines
modified:src/flask/config.py+5 added-1 removed
81 unmodified lines
8283 :param variable_name: name of the environment variable84 :param silent: set to ``True`` if you want silent failure for missing85 files.86 :return: bool. ``True`` if able to load config, ``False`` otherwise.86 :return: ``True`` if the file was loaded successfully.87 """88 rv = os.environ.get(variable_name)89 if not rv:90 if silent:
15 unmodified lines
106 absolute filename or a filename relative to the107 root path.108 :param silent: set to ``True`` if you want silent failure for missing109 files.110 :return: ``True`` if the file was loaded successfully.111112 .. versionadded:: 0.7113 `silent` parameter.114 """
70 unmodified lines
185 mapping of loaded data from the file.186 :type load: ``Callable[[Reader], Mapping]`` where ``Reader``187 implements a ``read`` method.188 :param silent: Ignore the file if it doesn't exist.189 :return: ``True`` if the file was loaded successfully.190191 .. versionadded:: 2.0192 """193 filename = os.path.join(self.root_path, filename)
16 unmodified lines
210211 :param filename: The path to the JSON file. This can be an212 absolute path or relative to the config root path.213 :param silent: Ignore the file if it doesn't exist.214 :return: ``True`` if the file was loaded successfully.215216 .. deprecated:: 2.0.0217 Will be removed in Flask 2.1. Use :meth:`from_file` instead.218 This was removed early in 2.0.0, was added back in 2.0.1.
15 unmodified lines
234 self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any235 ) -> bool:236 """Updates the config like :meth:`update` ignoring items with non-upper237 keys.238 :return: Always returns ``True``.239240 .. versionadded:: 0.11241 """242 mappings: t.Dict[str, t.Any] = {}
53 unmodified lines
modified:src/flask/scaffold.py+3 added-3 removed
90 unmodified lines
9192 def __init__(93 self,94 import_name: str,95 static_folder: t.Optional[str] = None,95 static_folder: t.Optional[t.Union[str, os.PathLike]] = None,96 static_url_path: t.Optional[str] = None,97 template_folder: t.Optional[str] = None,98 root_path: t.Optional[str] = None,99 ):100 #: The name of the package or module that this object belongs101 #: to. Do not change this once it is set by the constructor.102 self.import_name = import_name103104 self.static_folder = static_folder104 self.static_folder = static_folder # type: ignore105 self.static_url_path = static_url_path106107 #: The path to the templates folder, relative to108 #: :attr:`root_path`, to add to the template loader. ``None`` if
147 unmodified lines
256 else:257 return None258259 @static_folder.setter260 def static_folder(self, value: t.Optional[str]) -> None:260 def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None:261 if value is not None:262 value = os.fspath(value).rstrip(r"\/")263264 self._static_folder = value
611 unmodified lines
modified:tests/test_cli.py+27 added
15 unmodified lines
16from flask import Blueprint17from flask import current_app18from flask import Flask19from flask.cli import AppGroup20from flask.cli import DispatchingApp21from flask.cli import dotenv22from flask.cli import find_best_app23from flask.cli import FlaskGroup24from flask.cli import get_version
50 unmodified lines
75 assert app.name == "appname"7677 class Module:78 @staticmethod79 def create_app(**kwargs):80 return Flask("appname")8182 app = find_best_app(script_info, Module)83 assert isinstance(app, Flask)84 assert app.name == "appname"8586 class Module:87 @staticmethod88 def create_app(foo):89 return Flask("appname")9091 with pytest.deprecated_call(match="Script info"):
227 unmodified lines
319 app = obj.load_app()320 assert app.name == "testapp"321322323def test_lazy_load_error(monkeypatch):324 """When using lazy loading, the correct exception should be325 re-raised.326 """327328 class BadExc(Exception):329 pass330331 def bad_load():332 raise BadExc333334 lazy = DispatchingApp(bad_load, use_eager_loading=False)335336 with pytest.raises(BadExc):337 lazy._flush_bg_loading_exception()338339340def test_with_appcontext(runner):341 @click.command()342 @with_appcontext343 def testcmd():
345 unmodified lines
modified:tests/test_json.py+6 added
1import datetime2import decimal3import io4import uuid56import pytest
180 unmodified lines
187 rv_uuid = uuid.UUID(rv_x)188 assert rv_uuid == test_uuid189190191def test_json_decimal():192 rv = flask.json.dumps(decimal.Decimal("0.003"))193 assert rv == '"0.003"'194195196def test_json_attr(app, client):197 @app.route("/add", methods=["POST"])198 def add():199 json = flask.request.get_json()
209 unmodified lines
modified:CHANGES.rst+8 added
19 unmodified lines
20 decorators to accept functions with no arguments. :issue:`4098`21- Support View and MethodView instances with async handlers. :issue:`4112`22- Enhance typing of ``app.errorhandler`` decorator. :issue:`4095`23- Fix registering a blueprint twice with differing names. :issue:`4124`24- Fix the type of ``static_folder`` to accept ``pathlib.Path``.25 :issue:`4150`26- ``jsonify`` handles ``decimal.Decimal`` by encoding to ``str``.27 :issue:`4157`28- Correctly handle raising deferred errors in CLI lazy loading.29 :issue:`4096`30- The CLI loader handles ``**kwargs`` in a ``create_app`` function.31 :issue:`4170`323334Version 2.0.135-------------
1154 unmodified lines