Skip to content
Myr

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

26 files+99 added−128 removed

modified:examples/celery/pyproject.toml+3 added
modified:examples/javascript/js_example/views.py+1 added-1 removed
1from flask import jsonify2from flask import render_template3from flask import request45from js_example import app5from . import app678@app.route("/", defaults={"js": "fetch"})9@app.route("/<any(xhr, jquery, fetch):js>")
9 unmodified lines
modified:examples/javascript/pyproject.toml+3 added
modified:examples/tutorial/flaskr/__init__.py+3 added-2 removed
29 unmodified lines
30 def hello():31 return "Hello, World!"3233 # register the database commands34 from flaskr import db34 from . import db3536 db.init_app(app)3738 # apply the blueprints to the app39 from flaskr import auth, blog39 from . import auth40 from . import blog4142 app.register_blueprint(auth.bp)43 app.register_blueprint(blog.bp)44
7 unmodified lines
modified:examples/tutorial/flaskr/auth.py+1 added-1 removed
9 unmodified lines
10from flask import url_for11from werkzeug.security import check_password_hash12from werkzeug.security import generate_password_hash1314from flaskr.db import get_db14from .db import get_db1516bp = Blueprint("auth", __name__, url_prefix="/auth")1718
98 unmodified lines
modified:examples/tutorial/flaskr/blog.py+2 added-2 removed
5 unmodified lines
6from flask import request7from flask import url_for8from werkzeug.exceptions import abort910from flaskr.auth import login_required11from flaskr.db import get_db10from .auth import login_required11from .db import get_db1213bp = Blueprint("blog", __name__)1415
110 unmodified lines
modified:examples/tutorial/pyproject.toml+3 added
modified:src/flask/json/provider.py+1 added-3 removed
132 unmodified lines
133 - :class:`~markupsafe.Markup` (or any object with a ``__html__``134 method) will call the ``__html__`` method to get a string.135 """136137 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 lines
modified:src/flask/sansio/app.py+5 added-2 removed
33 unmodified lines
34from .scaffold import setupmethod3536if t.TYPE_CHECKING: # pragma: no cover37 from werkzeug.wrappers import Response as BaseResponse38 from .blueprints import Blueprint3839 from ..testing import FlaskClient40 from ..testing import FlaskCliRunner41 from .blueprints import Blueprint4243T_shell_context_processor = t.TypeVar(44 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable45)
859 unmodified lines
905 .. 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 )913914 def inject_url_defaults(self, endpoint: str, values: dict) -> None:915 """Injects the URL defaults for the given endpoint directly into
52 unmodified lines
modified:src/flask/app.py+6 added-3 removed
1181 unmodified lines
1182 # 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 lines
12721273 return response12741275 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 lines
13061307 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)13081309 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.13141315 When handling a request, the application context is popped
166 unmodified lines
modified:src/flask/helpers.py+2 added-3 removed
19 unmodified lines
20from .signals import message_flashed2122if t.TYPE_CHECKING: # pragma: no cover23 from werkzeug.wrappers import Response as BaseResponse2425 from .wrappers import Response262728def get_debug_flag() -> bool:
19 unmodified lines
48 return val.lower() in ("0", "false", "no")495051def 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 if
566 unmodified lines
modified:src/flask/sessions.py+2 added-1 removed
12 unmodified lines
13from .json.tag import TaggedJSONSerializer1415if t.TYPE_CHECKING: # pragma: no cover16 from .app import Flask17 from .wrappers import Request, Response17 from .wrappers import Request18 from .wrappers import Response192021class SessionMixin(MutableMapping):22 """Expands a basic dictionary with session attributes."""
346 unmodified lines
modified:src/flask/views.py-1 removed
4 unmodified lines
5from . import typing as ft6from .globals import current_app7from .globals import request899http_method_funcs = frozenset(10 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]11)12
177 unmodified lines
modified:tests/test_apps/subdomaintestmodule/__init__.py-1 removed
1from flask import Module233mod = Module(__name__, "foo", subdomain="foo")
modified:tests/typing/typing_app_decorators.py+2 added-4 removed
1from __future__ import annotations23import typing as t43from flask import Flask4from flask import Response56app = Flask(__name__)
19 unmodified lines
26 ...272829@app.teardown_appcontext32def teardown_sync(exc: t.Optional[BaseException]) -> None:30def teardown_sync(exc: BaseException | None) -> None:31 ...323334@app.teardown_appcontext37async def teardown_async(exc: t.Optional[BaseException]) -> None:35async def teardown_async(exc: BaseException | None) -> None:36 ...
modified:tests/typing/typing_route.py+2 added-2 removed
27 unmodified lines
28 return jsonify("Hello, World!")293031@app.route("/json/dict")32def hello_json_dict() -> t.Dict[str, t.Any]:32def hello_json_dict() -> dict[str, t.Any]:33 return {"response": "Hello, World!"}343536@app.route("/json/dict")37def hello_json_list() -> t.List[t.Any]:37def hello_json_list() -> list[t.Any]:38 return [{"message": "Hello"}, {"message": "World"}]394041class StatusJSON(t.TypedDict):
71 unmodified lines
modified:tests/test_appctx.py+3 added-6 removed
194 unmodified lines
195 called = []196197 @app.teardown_request198 def teardown_req(error=None):199 1 / 0199 raise ZeroDivisionError200201 @app.teardown_appcontext202 def teardown_app(error=None):203 called.append("TEARDOWN")204205 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 pass207208 assert called == ["flask_test", "TEARDOWN"]209 assert not flask.current_app
modified:tests/test_basic.py+13 added-11 removed
17 unmodified lines
18from werkzeug.routing import RequestRedirect1920import flask212222require_cpython_gc = pytest.mark.skipif(23 python_implementation() != "CPython",24 reason="Requires CPython GC behavior",25)
162 unmodified lines
188 assert random_uuid4 in rv.data.decode("utf-8")189190191def test_werkzeug_routing(app, client):193 from werkzeug.routing import Submount, Rule192 from werkzeug.routing import Rule193 from werkzeug.routing import Submount194195 app.url_map.add(196 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])197 )
11 unmodified lines
209 assert client.get("/foo/bar").data == b"bar"210211212def test_endpoint_decorator(app, client):213 from werkzeug.routing import Submount, Rule213 from werkzeug.routing import Rule214 from werkzeug.routing import Submount215216 app.url_map.add(217 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])218 )
212 unmodified lines
431 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 lines
784 pass785786 @app.route("/")787 def fails():787 1 // 0788 raise ZeroDivisionError789790 rv = client.get("/")791 assert rv.status_code == 500792 assert b"Internal Server Error" in rv.data
58 unmodified lines
851 flask.abort(404)852853 @app.route("/error")854 def error():854 1 // 0855 raise ZeroDivisionError856857 @app.route("/forbidden")858 def error2():859 flask.abort(403)
17 unmodified lines
877 return "internal server error", 500878879 @app.route("/")880 def broken_func():880 1 // 0881 raise ZeroDivisionError882883 @app.after_request884 def after_request(resp):885 resp.mimetype = "text/x-special"
161 unmodified lines
10471048 @app.before_request1049 def before_request():1050 if _trigger == "before":1050 1 // 01051 raise ZeroDivisionError10521053 @app.after_request1054 def after_request(response):1055 if _trigger == "after":1055 1 // 01056 raise ZeroDivisionError10571058 return response10591060 @app.route("/")1061 def index():
446 unmodified lines
1508 app.testing = False15091510 @app.route("/")1511 def index():1510 1 // 01512 raise ZeroDivisionError15131514 if key is not None:1515 app.config[key] = True1516
374 unmodified lines
modified:tests/test_blueprints.py+5 added-4 removed
632 unmodified lines
633634def test_context_processing(app, client):635 answer_bp = flask.Blueprint("answer_bp", __name__)636637 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 )642643 # App global context processor644 @answer_bp.app_context_processor645 def not_answer_context_processor():
409 unmodified lines
modified:tests/test_signals.py+2 added-2 removed
96 unmodified lines
97 recorded = []9899 @app.route("/")100 def index():101 1 // 0101 raise ZeroDivisionError102103 def record(sender, exception):104 recorded.append(exception)105
62 unmodified lines
168 recorded.append(exc)169170 @app.route("/")171 def index():172 1 // 0172 raise ZeroDivisionError173174 flask.appcontext_tearing_down.connect(record_teardown, app)175 try:176 rv = client.get("/")
5 unmodified lines
modified:tests/test_testing.py+4 added-7 removed
217 unmodified lines
218 return "Hello World!"219220 @app.route("/other")221 def other():222 1 // 0222 raise ZeroDivisionError223224 with client:225 resp = client.get("/")226 assert flask.g.value == 42227 assert resp.data == b"Hello World!"228 assert resp.status_code == 200229230 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 = 23236236 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: B018239240241def test_reuse_client(client):242 c = client
154 unmodified lines
modified:tests/test_views.py+2 added-2 removed
39 unmodified lines
4041def test_view_patching(app):42 class Index(flask.views.MethodView):43 def get(self):44 1 // 044 raise ZeroDivisionError4546 def post(self):47 1 // 047 raise ZeroDivisionError4849 class Other(Index):50 def get(self):51 return "GET"
209 unmodified lines
deleted:.flake8-25 removed
1[flake8]2extend-select =3 # bugbear4 B5 # bugbear opinions6 B97 # implicit str concat8 ISC9extend-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 B95022max-line-length = 8023per-file-ignores =24 # __init__ exports names25 src/flask/__init__.py: F401
modified:.gitignore+7 added-22 removed
1.DS_Store2.env3.flaskenv4*.pyc5*.pyo6env/7venv/8.venv/9env*10dist/11build/12*.egg13*.egg-info/14.tox/15.cache/16.pytest_cache/1.idea/18docs/_build/19.vscode2021# Coverage reports22htmlcov/2.vscode/3__pycache__/4.tox/5.coverage6.coverage.*25*,cover7htmlcov/8docs/_build/9dist/10venv/
modified:.pre-commit-config.yaml+6 added-23 removed
1ci:2 autoupdate_branch: "2.3.x"2 autoupdate_schedule: monthly3repos: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-fixer
modified:pyproject.toml+21 added
104 unmodified lines
105 "cryptography.*",106 "importlib_metadata",107]108ignore_missing_imports = true109110[tool.ruff]111src = ["src"]112fix = true113show-fixes = true114show-source = true115116[tool.ruff.lint]117select = [118 "B", # flake8-bugbear119 "E", # pycodestyle error120 "F", # pyflakes121 "I", # isort122 "UP", # pyupgrade123 "W", # pycodestyle warning124]125ignore-init-module-imports = true126127[tool.ruff.lint.isort]128force-single-line = true129order-by-type = false