use ruff linter and formatter
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 6edfd78 · Browse files · 26 files·+99 added−128 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+99 added−128 removed
- tests:+33 added−39 removed
- other:+66 added−89 removed
Provenance
- Commit
54ff9b2- Tree
3a242ae- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
6edfd78
26 files changed+99 added−128 removed
modified:examples/celery/pyproject.toml+3 added
10 unmodified lines1112131415161710 unmodified linesbuild-backend = "flit_core.buildapi"
[tool.flit.module]name = "task_app"
[tool.ruff]src = ["src"]modified:examples/javascript/js_example/views.py+1 added-1 removed
1 from flask import jsonify2 from flask import render_template3 from flask import request4 5-from js_example import app5+from . import app6 7 8 @app.route("/", defaults={"js": "fetch"})9 @app.route("/<any(xhr, jquery, fetch):js>")9 unmodified linesmodified:examples/javascript/pyproject.toml+3 added
25 unmodified lines2627282930313225 unmodified lines
[tool.coverage.run]branch = truesource = ["js_example", "tests"]
[tool.ruff]src = ["src"]modified:examples/tutorial/flaskr/__init__.py+3 added-2 removed
29 unmodified lines30 def hello():31 return "Hello, World!"32 33 # register the database commands34- from flaskr import db34+ from . import db35 36 db.init_app(app)37 38 # apply the blueprints to the app39- from flaskr import auth, blog39+ from . import auth40+ from . import blog41 42 app.register_blueprint(auth.bp)43 app.register_blueprint(blog.bp)44 7 unmodified linesmodified:examples/tutorial/flaskr/auth.py+1 added-1 removed
9 unmodified lines10 from flask import url_for11 from werkzeug.security import check_password_hash12 from werkzeug.security import generate_password_hash13 14-from flaskr.db import get_db14+from .db import get_db15 16 bp = Blueprint("auth", __name__, url_prefix="/auth")17 18 98 unmodified linesmodified:examples/tutorial/flaskr/blog.py+2 added-2 removed
5 unmodified lines6 from flask import request7 from flask import url_for8 from werkzeug.exceptions import abort9 10-from flaskr.auth import login_required11-from flaskr.db import get_db10+from .auth import login_required11+from .db import get_db12 13 bp = Blueprint("blog", __name__)14 15 110 unmodified linesmodified:examples/tutorial/pyproject.toml+3 added
32 unmodified lines3334353637383932 unmodified lines
[tool.coverage.run]branch = truesource = ["flaskr", "tests"]
[tool.ruff]src = ["src"]modified:src/flask/json/provider.py+1 added-3 removed
132 unmodified lines133 - :class:`~markupsafe.Markup` (or any object with a ``__html__``134 method) will call the ``__html__`` method to get a string.135 """136 137- default: t.Callable[[t.Any], t.Any] = staticmethod(138- _default139- ) # type: ignore[assignment]137+ default: t.Callable[[t.Any], t.Any] = staticmethod(_default) # type: ignore[assignment]138 """Apply this function to any object that :meth:`json.dumps` does139 not know how to serialize. It should return a valid JSON type or140 raise a ``TypeError``.141 """73 unmodified linesmodified:src/flask/sansio/app.py+5 added-2 removed
33 unmodified lines34 from .scaffold import setupmethod35 36 if t.TYPE_CHECKING: # pragma: no cover37 from werkzeug.wrappers import Response as BaseResponse38- from .blueprints import Blueprint38+39 from ..testing import FlaskClient40 from ..testing import FlaskCliRunner41+ from .blueprints import Blueprint42 43 T_shell_context_processor = t.TypeVar(44 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable45 )859 unmodified lines905 .. versionadded:: 2.2906 Moved from ``flask.redirect``, which calls this method.907 """908 return _wz_redirect(908- location, code=code, Response=self.response_class # type: ignore[arg-type]909+ location,910+ code=code,911+ Response=self.response_class, # type: ignore[arg-type]912 )913 914 def inject_url_defaults(self, endpoint: str, values: dict) -> None:915 """Injects the URL defaults for the given endpoint directly into52 unmodified linesmodified:src/flask/app.py+6 added-3 removed
1181 unmodified lines1182 # evaluate a WSGI callable, or coerce a different response1183 # class to the correct type1184 try:1185 rv = self.response_class.force_type(1186- rv, request.environ # type: ignore[arg-type]1186+ rv, # type: ignore[arg-type]1187+ request.environ,1188 )1189 except TypeError as e:1190 raise TypeError(1191 f"{e}\nThe view function did not return a valid"80 unmodified lines1272 1273 return response1274 1275 def do_teardown_request(1275- self, exc: BaseException | None = _sentinel # type: ignore1276+ self,1277+ exc: BaseException | None = _sentinel, # type: ignore[assignment]1278 ) -> None:1279 """Called after the request is dispatched and the response is1280 returned, right before the request context is popped.1281 24 unmodified lines1306 1307 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1308 1309 def do_teardown_appcontext(1308- self, exc: BaseException | None = _sentinel # type: ignore1310+ self,1311+ exc: BaseException | None = _sentinel, # type: ignore[assignment]1312 ) -> None:1313 """Called right before the application context is popped.1314 1315 When handling a request, the application context is popped166 unmodified linesmodified:src/flask/helpers.py+2 added-3 removed
19 unmodified lines20 from .signals import message_flashed21 22 if t.TYPE_CHECKING: # pragma: no cover23 from werkzeug.wrappers import Response as BaseResponse24+25 from .wrappers import Response26 27 28 def get_debug_flag() -> bool:19 unmodified lines48 return val.lower() in ("0", "false", "no")49 50 51 def stream_with_context(51- generator_or_function: (52- t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]]53- )52+ generator_or_function: t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]]53 ) -> t.Iterator[t.AnyStr]:54 """Request contexts disappear when the response is started on the server.55 This is done for efficiency reasons and to make it less likely to encounter56 memory leaks with badly written WSGI middlewares. The downside is that if566 unmodified linesmodified:src/flask/sessions.py+2 added-1 removed
12 unmodified lines13 from .json.tag import TaggedJSONSerializer14 15 if t.TYPE_CHECKING: # pragma: no cover16 from .app import Flask17- from .wrappers import Request, Response17+ from .wrappers import Request18+ from .wrappers import Response19 20 21 class SessionMixin(MutableMapping):22 """Expands a basic dictionary with session attributes."""346 unmodified linesmodified:src/flask/views.py-1 removed
4 unmodified lines5 from . import typing as ft6 from .globals import current_app7 from .globals import request8 9-9 http_method_funcs = frozenset(10 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]11 )12 177 unmodified linesmodified:tests/test_apps/subdomaintestmodule/__init__.py-1 removed
1 from flask import Module2 3-3 mod = Module(__name__, "foo", subdomain="foo")modified:tests/typing/typing_app_decorators.py+2 added-4 removed
1 from __future__ import annotations2 3-import typing as t4-3 from flask import Flask4 from flask import Response5 6 app = Flask(__name__)19 unmodified lines26 ...27 28 29 @app.teardown_appcontext32-def teardown_sync(exc: t.Optional[BaseException]) -> None:30+def teardown_sync(exc: BaseException | None) -> None:31 ...32 33 34 @app.teardown_appcontext37-async def teardown_async(exc: t.Optional[BaseException]) -> None:35+async def teardown_async(exc: BaseException | None) -> None:36 ...modified:tests/typing/typing_route.py+2 added-2 removed
27 unmodified lines28 return jsonify("Hello, World!")29 30 31 @app.route("/json/dict")32-def hello_json_dict() -> t.Dict[str, t.Any]:32+def hello_json_dict() -> dict[str, t.Any]:33 return {"response": "Hello, World!"}34 35 36 @app.route("/json/dict")37-def hello_json_list() -> t.List[t.Any]:37+def hello_json_list() -> list[t.Any]:38 return [{"message": "Hello"}, {"message": "World"}]39 40 41 class StatusJSON(t.TypedDict):71 unmodified linesmodified:tests/test_appctx.py+3 added-6 removed
194 unmodified lines195 called = []196 197 @app.teardown_request198 def teardown_req(error=None):199- 1 / 0199+ raise ZeroDivisionError200 201 @app.teardown_appcontext202 def teardown_app(error=None):203 called.append("TEARDOWN")204 205- try:206- with app.test_request_context():207- called.append(flask.current_app.name)205+ with app.app_context():206+ called.append(flask.current_app.name)208- except ZeroDivisionError:209- pass207 208 assert called == ["flask_test", "TEARDOWN"]209 assert not flask.current_appmodified:tests/test_basic.py+13 added-11 removed
17 unmodified lines18 from werkzeug.routing import RequestRedirect19 20 import flask21 22-22 require_cpython_gc = pytest.mark.skipif(23 python_implementation() != "CPython",24 reason="Requires CPython GC behavior",25 )162 unmodified lines188 assert random_uuid4 in rv.data.decode("utf-8")189 190 191 def test_werkzeug_routing(app, client):193- from werkzeug.routing import Submount, Rule192+ from werkzeug.routing import Rule193+ from werkzeug.routing import Submount194 195 app.url_map.add(196 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])197 )11 unmodified lines209 assert client.get("/foo/bar").data == b"bar"210 211 212 def test_endpoint_decorator(app, client):213- from werkzeug.routing import Submount, Rule213+ from werkzeug.routing import Rule214+ from werkzeug.routing import Submount215 216 app.url_map.add(217 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])218 )212 unmodified lines431 with client:432 client.get("/")433 s = flask.session434 assert s["t"] == (1, 2, 3)434- assert type(s["b"]) is bytes435+ assert type(s["b"]) is bytes # noqa: E721436 assert s["b"] == b"\xff"436- assert type(s["m"]) is Markup437+ assert type(s["m"]) is Markup # noqa: E721438 assert s["m"] == Markup("<html>")439 assert s["u"] == the_uuid440 assert s["d"] == now441 assert s["t_tag"] == {" t": "not-a-tuple"}342 unmodified lines784 pass785 786 @app.route("/")787 def fails():787- 1 // 0788+ raise ZeroDivisionError789 790 rv = client.get("/")791 assert rv.status_code == 500792 assert b"Internal Server Error" in rv.data58 unmodified lines851 flask.abort(404)852 853 @app.route("/error")854 def error():854- 1 // 0855+ raise ZeroDivisionError856 857 @app.route("/forbidden")858 def error2():859 flask.abort(403)17 unmodified lines877 return "internal server error", 500878 879 @app.route("/")880 def broken_func():880- 1 // 0881+ raise ZeroDivisionError882 883 @app.after_request884 def after_request(resp):885 resp.mimetype = "text/x-special"161 unmodified lines1047 1048 @app.before_request1049 def before_request():1050 if _trigger == "before":1050- 1 // 01051+ raise ZeroDivisionError1052 1053 @app.after_request1054 def after_request(response):1055 if _trigger == "after":1055- 1 // 01056+ raise ZeroDivisionError1057+1058 return response1059 1060 @app.route("/")1061 def index():446 unmodified lines1508 app.testing = False1509 1510 @app.route("/")1511 def index():1510- 1 // 01512+ raise ZeroDivisionError1513 1514 if key is not None:1515 app.config[key] = True1516 374 unmodified linesmodified:tests/test_blueprints.py+5 added-4 removed
632 unmodified lines633 634 def test_context_processing(app, client):635 answer_bp = flask.Blueprint("answer_bp", __name__)636 637+ def template_string():637- template_string = lambda: flask.render_template_string( # noqa: E731638- "{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}"639- "{% if answer %}{{ answer }} is the answer.{% endif %}"640- )638+ return flask.render_template_string(639+ "{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}"640+ "{% if answer %}{{ answer }} is the answer.{% endif %}"641+ )642 643 # App global context processor644 @answer_bp.app_context_processor645 def not_answer_context_processor():409 unmodified linesmodified:tests/test_signals.py+2 added-2 removed
96 unmodified lines97 recorded = []98 99 @app.route("/")100 def index():101- 1 // 0101+ raise ZeroDivisionError102 103 def record(sender, exception):104 recorded.append(exception)105 62 unmodified lines168 recorded.append(exc)169 170 @app.route("/")171 def index():172- 1 // 0172+ raise ZeroDivisionError173 174 flask.appcontext_tearing_down.connect(record_teardown, app)175 try:176 rv = client.get("/")5 unmodified linesmodified:tests/test_testing.py+4 added-7 removed
217 unmodified lines218 return "Hello World!"219 220 @app.route("/other")221 def other():222- 1 // 0222+ raise ZeroDivisionError223 224 with client:225 resp = client.get("/")226 assert flask.g.value == 42227 assert resp.data == b"Hello World!"228 assert resp.status_code == 200229 230+ with client:231 resp = client.get("/other")232 assert not hasattr(flask.g, "value")233 assert b"Internal Server Error" in resp.data234 assert resp.status_code == 500235 flask.g.value = 23236 236- try:237- flask.g.value238- except (AttributeError, RuntimeError):239- pass240- else:241- raise AssertionError("some kind of exception expected")237+ with pytest.raises(RuntimeError):238+ flask.g.value # noqa: B018239 240 241 def test_reuse_client(client):242 c = client154 unmodified linesmodified:tests/test_views.py+2 added-2 removed
39 unmodified lines40 41 def test_view_patching(app):42 class Index(flask.views.MethodView):43 def get(self):44- 1 // 044+ raise ZeroDivisionError45 46 def post(self):47- 1 // 047+ raise ZeroDivisionError48 49 class Other(Index):50 def get(self):51 return "GET"209 unmodified linesdeleted:.flake8-25 removed
1-[flake8]2-extend-select =3- # bugbear4- B5- # bugbear opinions6- B97- # implicit str concat8- ISC9-extend-ignore =10- # slice notation whitespace, invalid11- E20312- # line length, handled by bugbear B95013- E50114- # bare except, handled by bugbear B00115- E72216- # zip with strict=, requires python >= 3.1017- B90518- # string formatting opinion, B028 renamed to B90719- B02820- B90721-# up to 88 allowed by bugbear B95022-max-line-length = 8023-per-file-ignores =24- # __init__ exports names25- src/flask/__init__.py: F401modified:.gitignore+7 added-22 removed
1-.DS_Store2-.env3-.flaskenv4-*.pyc5-*.pyo6-env/7-venv/8-.venv/9-env*10-dist/11-build/12-*.egg13-*.egg-info/14-.tox/15-.cache/16-.pytest_cache/1 .idea/18-docs/_build/19-.vscode20-21-# Coverage reports22-htmlcov/2+.vscode/3+__pycache__/4+.tox/5 .coverage6 .coverage.*25-*,cover7+htmlcov/8+docs/_build/9+dist/10+venv/modified:.pre-commit-config.yaml+6 added-23 removed
1 ci:2- autoupdate_branch: "2.3.x"2 autoupdate_schedule: monthly3 repos:5- - repo: https://github.com/asottile/pyupgrade6- rev: v3.10.14+ - repo: https://github.com/astral-sh/ruff-pre-commit5+ rev: v0.1.36 hooks:8- - id: pyupgrade9- args: ["--py38-plus"]10- - repo: https://github.com/asottile/reorder-python-imports11- rev: v3.10.012- hooks:13- - id: reorder-python-imports14- name: Reorder Python imports (src, tests)15- files: "^(?!examples/)"16- args: ["--application-directories", "src"]17- - repo: https://github.com/psf/black18- rev: 23.7.019- hooks:20- - id: black21- - repo: https://github.com/PyCQA/flake822- rev: 6.1.023- hooks:24- - id: flake825- additional_dependencies:26- - flake8-bugbear27- - flake8-implicit-str-concat7+ - id: ruff8+ - id: ruff-format9 - repo: https://github.com/pre-commit/pre-commit-hooks10 rev: v4.4.011 hooks:12+ - id: check-merge-conflict13+ - id: debug-statements14 - id: fix-byte-order-marker15 - id: trailing-whitespace16 - id: end-of-file-fixermodified:pyproject.toml+21 added
104 unmodified lines105 "cryptography.*",106 "importlib_metadata",107 ]108 ignore_missing_imports = true109+110+[tool.ruff]111+src = ["src"]112+fix = true113+show-fixes = true114+show-source = true115+116+[tool.ruff.lint]117+select = [118+ "B", # flake8-bugbear119+ "E", # pycodestyle error120+ "F", # pyflakes121+ "I", # isort122+ "UP", # pyupgrade123+ "W", # pycodestyle warning124+]125+ignore-init-module-imports = true126+127+[tool.ruff.lint.isort]128+force-single-line = true129+order-by-type = false