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
Provenance
- Commit
afc13b9- Tree
77ed717- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
0826be4- Parent 2
ef3a82a
17 files changed+138 added−78 removed
modified:docs/deploying/asgi.rst+2 added-2 removed
3 unmodified lines4 ====5 6 If you'd like to use an ASGI server you will need to utilise WSGI to7 ASGI middleware. The asgiref8-[WsgiToAsgi](https://github.com/django/asgiref#wsgi-to-asgi-adapter)8+`WsgiToAsgi <https://github.com/django/asgiref#wsgi-to-asgi-adapter>`_9 adapter is recommended as it integrates with the event loop used for10 Flask's :ref:`async_await` support. You can use the adapter by11 wrapping the Flask app,12 7 unmodified lines20 ...21 22 asgi_app = WsgiToAsgi(app)23 24-and then serving the ``asgi_app`` with the asgi server, e.g. using24+and then serving the ``asgi_app`` with the ASGI server, e.g. using25 `Hypercorn <https://gitlab.com/pgjones/hypercorn>`_,26 27 .. sourcecode:: text28 1 unmodified linemodified:docs/patterns/jquery.rst+3 added-4 removed
21 unmodified lines22 to add a script statement to the bottom of your ``<body>`` to load jQuery:23 24 .. sourcecode:: html25 26- <script type=text/javascript src="{{27- url_for('static', filename='jquery.js') }}"></script>26+ <script src="{{ url_for('static', filename='jquery.js') }}"></script>27 28 Another method is using Google's `AJAX Libraries API29 <https://developers.google.com/speed/libraries/>`_ to load jQuery:30 26 unmodified lines57 like this:58 59 .. sourcecode:: html+jinja60 62- <script type=text/javascript>61+ <script>62 $SCRIPT_ROOT = {{ request.script_root|tojson }};63 </script>64 65 41 unmodified lines107 usually a better idea to have that in a separate script file:108 109 .. sourcecode:: html110 112- <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 linesmodified:docs/tutorial/tests.rst+1 added-1 removed
268 unmodified lines269 assert 'http://localhost/auth/login' == response.headers['Location']270 271 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 None275 276 277 @pytest.mark.parametrize(('username', 'password', 'message'), (284 unmodified linesmodified:docs/tutorial/views.rst+32 added-28 removed
89 unmodified lines90 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."94 95 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"))106 107 flash(error)108 109 return render_template('auth/register.html')14 unmodified lines124 input their ``username`` and ``password``.125 126 #. Validate that ``username`` and ``password`` are not empty.127 128-#. 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.129 136- :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*.135 141-#. 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.143 144+ - An :exc:`sqlite3.IntegrityError` will occur if the username145+ already exists, which should be shown to the user as another146+ validation error.147+148 #. 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 to46 unmodified lines198 There are a few differences from the ``register`` view:199 200 #. The user is queried first and stored in a variable for later use.201 202+ :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.206+207 #. :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 linesmodified:docs/api.rst+1 added-1 removed
254 unmodified lines255 the filter to render data inside ``<script>`` tags.256 257 .. sourcecode:: html+jinja258 259- <script type=text/javascript>259+ <script>260 const names = {{ names|tosjon }};261 renderChart(names, {{ axis_data|tojson }});262 </script>263 512 unmodified linesmodified:docs/quickstart.rst+1 added-1 removed
624 unmodified lines625 @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 ...631 632 For some better examples, see :doc:`patterns/fileuploads`.633 305 unmodified linesmodified:examples/tutorial/flaskr/auth.py+13 added-13 removed
58 unmodified lines59 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."63 64 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"))78 79 flash(error)80 81 return render_template("auth/register.html")35 unmodified linesmodified:examples/tutorial/tests/test_auth.py+1 added-1 removed
14 unmodified lines15 16 # 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 )22 23 46 unmodified linesmodified:src/flask/json/__init__.py+8 added-1 removed
1+import decimal2 import io3 import json as _json4 import typing as t5 import uuid41 unmodified lines47 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 lines117 :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`.120 121+ .. versionchanged:: 2.0.2122+ :class:`decimal.Decimal` is supported by converting to a string.123+124 .. versionchanged:: 2.0125 ``encoding`` is deprecated and will be removed in Flask 2.1.126 127 .. versionchanged:: 1.0.3199 unmodified lines327 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.330 331+ .. versionchanged:: 2.0.2332+ :class:`decimal.Decimal` is supported by converting to a string.333+334 .. 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 linesmodified:src/flask/app.py+1 added-1 removed
387 unmodified lines388 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 linesmodified:src/flask/blueprints.py+2 added-1 removed
1+import os2 import typing as t3 from collections import defaultdict4 from functools import update_wrapper5 169 unmodified lines175 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 linesmodified:src/flask/cli.py+24 added-20 removed
101 unmodified lines102 DeprecationWarning,103 )104 kwargs["script_info"] = script_info105 106- 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()))108 109+ 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)121+122 return app_factory(*args, **kwargs)123 124 125 def _called_with_wrong_args(f):188 unmodified lines314 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 = None319 320 if use_eager_loading is None:321 use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"322 7 unmodified lines330 __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 = e336 337 t = Thread(target=_load_app, args=())338 t.start()339 340 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_exc343 344+ if exc is not None:345+ self._bg_loading_exc = None346+ raise exc347+348 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 rv353 354 def __call__(self, environ, start_response):355 __traceback_hide__ = True # noqa: F841643 unmodified linesmodified:src/flask/config.py+5 added-1 removed
81 unmodified lines82 83 :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 lines106 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.111 112 .. versionadded:: 0.7113 `silent` parameter.114 """70 unmodified lines185 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.190 191 .. versionadded:: 2.0192 """193 filename = os.path.join(self.root_path, filename)16 unmodified lines210 211 :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.215 216 .. 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 lines234 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``.239 240 .. versionadded:: 0.11241 """242 mappings: t.Dict[str, t.Any] = {}53 unmodified linesmodified:src/flask/scaffold.py+3 added-3 removed
90 unmodified lines91 92 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_name103 104- self.static_folder = static_folder104+ self.static_folder = static_folder # type: ignore105 self.static_url_path = static_url_path106 107 #: The path to the templates folder, relative to108 #: :attr:`root_path`, to add to the template loader. ``None`` if147 unmodified lines256 else:257 return None258 259 @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"\/")263 264 self._static_folder = value611 unmodified linesmodified:tests/test_cli.py+27 added
15 unmodified lines16 from flask import Blueprint17 from flask import current_app18 from flask import Flask19 from flask.cli import AppGroup20+from flask.cli import DispatchingApp21 from flask.cli import dotenv22 from flask.cli import find_best_app23 from flask.cli import FlaskGroup24 from flask.cli import get_version50 unmodified lines75 assert app.name == "appname"76 77 class Module:78 @staticmethod79+ def create_app(**kwargs):80+ return Flask("appname")81+82+ app = find_best_app(script_info, Module)83+ assert isinstance(app, Flask)84+ assert app.name == "appname"85+86+ class Module:87+ @staticmethod88 def create_app(foo):89 return Flask("appname")90 91 with pytest.deprecated_call(match="Script info"):227 unmodified lines319 app = obj.load_app()320 assert app.name == "testapp"321 322 323+def test_lazy_load_error(monkeypatch):324+ """When using lazy loading, the correct exception should be325+ re-raised.326+ """327+328+ class BadExc(Exception):329+ pass330+331+ def bad_load():332+ raise BadExc333+334+ lazy = DispatchingApp(bad_load, use_eager_loading=False)335+336+ with pytest.raises(BadExc):337+ lazy._flush_bg_loading_exception()338+339+340 def test_with_appcontext(runner):341 @click.command()342 @with_appcontext343 def testcmd():345 unmodified linesmodified:tests/test_json.py+6 added
1 import datetime2+import decimal3 import io4 import uuid5 6 import pytest180 unmodified lines187 rv_uuid = uuid.UUID(rv_x)188 assert rv_uuid == test_uuid189 190 191+def test_json_decimal():192+ rv = flask.json.dumps(decimal.Decimal("0.003"))193+ assert rv == '"0.003"'194+195+196 def test_json_attr(app, client):197 @app.route("/add", methods=["POST"])198 def add():199 json = flask.request.get_json()209 unmodified linesmodified:CHANGES.rst+8 added
19 unmodified lines20 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`32 33 34 Version 2.0.135 -------------1154 unmodified lines