From dde76ea960174f13929c7a10e323002375f9f09e Mon Sep 17 00:00:00 2001 From: Mark Mayo Date: Thu, 13 Oct 2022 18:15:15 +1300 Subject: [PATCH] pylint issues resolved Ran tests, and black afterwards. Updated changes.rst and included pre-commit hooks as required. Ran isort on imports. --- CHANGES.rst | 2 +- examples/javascript/js_example/__init__.py | 4 +- examples/javascript/js_example/views.py | 6 +- examples/javascript/tests/conftest.py | 1 - examples/javascript/tests/test_js_example.py | 1 + examples/tutorial/flaskr/auth.py | 23 +++--- examples/tutorial/flaskr/blog.py | 12 +-- examples/tutorial/flaskr/db.py | 4 +- examples/tutorial/tests/conftest.py | 4 +- examples/tutorial/tests/test_auth.py | 5 +- examples/tutorial/tests/test_blog.py | 1 - examples/tutorial/tests/test_db.py | 1 - src/flask/__init__.py | 82 ++++++++++--------- src/flask/app.py | 6 +- src/flask/cli.py | 13 ++- src/flask/config.py | 2 +- src/flask/ctx.py | 3 +- src/flask/debughelpers.py | 2 +- src/flask/globals.py | 4 +- src/flask/helpers.py | 5 +- src/flask/scaffold.py | 16 ++-- src/flask/sessions.py | 1 + src/flask/views.py | 1 - src/flask/wrappers.py | 3 +- tests/conftest.py | 2 +- tests/test_apps/blueprintapp/__init__.py | 6 +- .../test_apps/subdomaintestmodule/__init__.py | 1 - tests/test_basic.py | 15 ++-- tests/test_blueprints.py | 4 +- tests/test_cli.py | 6 +- tests/test_config.py | 1 - tests/test_reqctx.py | 9 +- 32 files changed, 114 insertions(+), 132 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 6c3ff32c..8362f2b6 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -7,7 +7,7 @@ Unreleased Version 2.2.3 ------------- -Unreleased +- tidy up of pylint issues across several files Version 2.2.2 diff --git a/examples/javascript/js_example/__init__.py b/examples/javascript/js_example/__init__.py index 068b2d98..e0155e1c 100644 --- a/examples/javascript/js_example/__init__.py +++ b/examples/javascript/js_example/__init__.py @@ -1,5 +1,5 @@ +from js_example import views # noqa: F401 + from flask import Flask app = Flask(__name__) - -from js_example import views # noqa: F401 diff --git a/examples/javascript/js_example/views.py b/examples/javascript/js_example/views.py index 0d4b6561..7cffca8b 100644 --- a/examples/javascript/js_example/views.py +++ b/examples/javascript/js_example/views.py @@ -1,9 +1,7 @@ -from flask import jsonify -from flask import render_template -from flask import request - from js_example import app +from flask import jsonify, render_template, request + @app.route("/", defaults={"js": "fetch"}) @app.route("/") diff --git a/examples/javascript/tests/conftest.py b/examples/javascript/tests/conftest.py index e0cabbfd..e5b2838a 100644 --- a/examples/javascript/tests/conftest.py +++ b/examples/javascript/tests/conftest.py @@ -1,5 +1,4 @@ import pytest - from js_example import app diff --git a/examples/javascript/tests/test_js_example.py b/examples/javascript/tests/test_js_example.py index d155ad5c..d6d41975 100644 --- a/examples/javascript/tests/test_js_example.py +++ b/examples/javascript/tests/test_js_example.py @@ -1,4 +1,5 @@ import pytest + from flask import template_rendered diff --git a/examples/tutorial/flaskr/auth.py b/examples/tutorial/flaskr/auth.py index b423e6ae..29f17dac 100644 --- a/examples/tutorial/flaskr/auth.py +++ b/examples/tutorial/flaskr/auth.py @@ -1,17 +1,18 @@ import functools -from flask import Blueprint -from flask import flash -from flask import g -from flask import redirect -from flask import render_template -from flask import request -from flask import session -from flask import url_for -from werkzeug.security import check_password_hash -from werkzeug.security import generate_password_hash - from flaskr.db import get_db +from werkzeug.security import check_password_hash, generate_password_hash + +from flask import ( + Blueprint, + flash, + g, + redirect, + render_template, + request, + session, + url_for, +) bp = Blueprint("auth", __name__, url_prefix="/auth") diff --git a/examples/tutorial/flaskr/blog.py b/examples/tutorial/flaskr/blog.py index 3704626b..14ab636f 100644 --- a/examples/tutorial/flaskr/blog.py +++ b/examples/tutorial/flaskr/blog.py @@ -1,14 +1,8 @@ -from flask import Blueprint -from flask import flash -from flask import g -from flask import redirect -from flask import render_template -from flask import request -from flask import url_for -from werkzeug.exceptions import abort - from flaskr.auth import login_required from flaskr.db import get_db +from werkzeug.exceptions import abort + +from flask import Blueprint, flash, g, redirect, render_template, request, url_for bp = Blueprint("blog", __name__) diff --git a/examples/tutorial/flaskr/db.py b/examples/tutorial/flaskr/db.py index acaa4ae3..54297b9f 100644 --- a/examples/tutorial/flaskr/db.py +++ b/examples/tutorial/flaskr/db.py @@ -1,8 +1,8 @@ import sqlite3 import click -from flask import current_app -from flask import g + +from flask import current_app, g def get_db(): diff --git a/examples/tutorial/tests/conftest.py b/examples/tutorial/tests/conftest.py index 6bf62f0a..68804498 100644 --- a/examples/tutorial/tests/conftest.py +++ b/examples/tutorial/tests/conftest.py @@ -2,10 +2,8 @@ import os import tempfile import pytest - from flaskr import create_app -from flaskr.db import get_db -from flaskr.db import init_db +from flaskr.db import get_db, init_db # read in SQL for populating test data with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f: diff --git a/examples/tutorial/tests/test_auth.py b/examples/tutorial/tests/test_auth.py index 76db62f7..e302dc13 100644 --- a/examples/tutorial/tests/test_auth.py +++ b/examples/tutorial/tests/test_auth.py @@ -1,9 +1,8 @@ import pytest -from flask import g -from flask import session - from flaskr.db import get_db +from flask import g, session + def test_register(client, app): # test that viewing the page renders without template errors diff --git a/examples/tutorial/tests/test_blog.py b/examples/tutorial/tests/test_blog.py index 55c769d8..929a63bb 100644 --- a/examples/tutorial/tests/test_blog.py +++ b/examples/tutorial/tests/test_blog.py @@ -1,5 +1,4 @@ import pytest - from flaskr.db import get_db diff --git a/examples/tutorial/tests/test_db.py b/examples/tutorial/tests/test_db.py index 2363bf81..9c073965 100644 --- a/examples/tutorial/tests/test_db.py +++ b/examples/tutorial/tests/test_db.py @@ -1,7 +1,6 @@ import sqlite3 import pytest - from flaskr.db import get_db diff --git a/src/flask/__init__.py b/src/flask/__init__.py index 185a465a..08538bb8 100644 --- a/src/flask/__init__.py +++ b/src/flask/__init__.py @@ -1,46 +1,46 @@ from markupsafe import escape from markupsafe import Markup -from . import json as json -from .app import Flask as Flask -from .app import Request as Request -from .app import Response as Response -from .blueprints import Blueprint as Blueprint -from .config import Config as Config -from .ctx import after_this_request as after_this_request -from .ctx import copy_current_request_context as copy_current_request_context -from .ctx import has_app_context as has_app_context -from .ctx import has_request_context as has_request_context -from .globals import current_app as current_app -from .globals import g as g -from .globals import request as request -from .globals import session as session -from .helpers import abort as abort -from .helpers import flash as flash -from .helpers import get_flashed_messages as get_flashed_messages -from .helpers import get_template_attribute as get_template_attribute -from .helpers import make_response as make_response -from .helpers import redirect as redirect -from .helpers import send_file as send_file -from .helpers import send_from_directory as send_from_directory -from .helpers import stream_with_context as stream_with_context -from .helpers import url_for as url_for -from .json import jsonify as jsonify -from .signals import appcontext_popped as appcontext_popped -from .signals import appcontext_pushed as appcontext_pushed -from .signals import appcontext_tearing_down as appcontext_tearing_down -from .signals import before_render_template as before_render_template -from .signals import got_request_exception as got_request_exception -from .signals import message_flashed as message_flashed -from .signals import request_finished as request_finished -from .signals import request_started as request_started -from .signals import request_tearing_down as request_tearing_down -from .signals import signals_available as signals_available -from .signals import template_rendered as template_rendered -from .templating import render_template as render_template -from .templating import render_template_string as render_template_string -from .templating import stream_template as stream_template -from .templating import stream_template_string as stream_template_string +from . import json +from .app import Flask +from .app import Request +from .app import Response +from .blueprints import Blueprint +from .config import Config +from .ctx import after_this_request +from .ctx import copy_current_request_context +from .ctx import has_app_context +from .ctx import has_request_context +from .globals import current_app +from .globals import g +from .globals import request +from .globals import session +from .helpers import abort +from .helpers import flash +from .helpers import get_flashed_messages +from .helpers import get_template_attribute +from .helpers import make_response +from .helpers import redirect +from .helpers import send_file +from .helpers import send_from_directory +from .helpers import stream_with_context +from .helpers import url_for +from .json import jsonify +from .signals import appcontext_popped +from .signals import appcontext_pushed +from .signals import appcontext_tearing_down +from .signals import before_render_template +from .signals import got_request_exception +from .signals import message_flashed +from .signals import request_finished +from .signals import request_started +from .signals import request_tearing_down +from .signals import signals_available +from .signals import template_rendered +from .templating import render_template +from .templating import render_template_string +from .templating import stream_template +from .templating import stream_template_string __version__ = "2.3.0.dev" @@ -48,6 +48,7 @@ __version__ = "2.3.0.dev" def __getattr__(name): if name == "_app_ctx_stack": import warnings + from .globals import __app_ctx_stack warnings.warn( @@ -59,6 +60,7 @@ def __getattr__(name): if name == "_request_ctx_stack": import warnings + from .globals import __request_ctx_stack warnings.warn( diff --git a/src/flask/app.py b/src/flask/app.py index ce4dcf6a..4a20f184 100644 --- a/src/flask/app.py +++ b/src/flask/app.py @@ -71,9 +71,9 @@ from .wrappers import Response if t.TYPE_CHECKING: # pragma: no cover import typing_extensions as te + from .blueprints import Blueprint - from .testing import FlaskClient - from .testing import FlaskCliRunner + from .testing import FlaskClient, FlaskCliRunner T_before_first_request = t.TypeVar( "T_before_first_request", bound=ft.BeforeFirstRequestCallable @@ -866,7 +866,7 @@ class Flask(Scaffold): subfolders use forward slashes as separator. :param mode: resource file opening mode, default is 'rb'. """ - return open(os.path.join(self.instance_path, resource), mode) + return open(os.path.join(self.instance_path, resource), mode, encoding="utf-8") @property def templates_auto_reload(self) -> bool: diff --git a/src/flask/cli.py b/src/flask/cli.py index 82fe8194..f5c6a557 100644 --- a/src/flask/cli.py +++ b/src/flask/cli.py @@ -47,7 +47,7 @@ def find_best_app(module): if len(matches) == 1: return matches[0] - elif len(matches) > 1: + if len(matches) > 1: raise NoAppException( "Detected multiple Flask applications in module" f" '{module.__name__}'. Use '{module.__name__}:name'" @@ -224,17 +224,15 @@ def locate_app(module_name, app_name, raise_if_not_found=True): f"While importing {module_name!r}, an ImportError was" f" raised:\n\n{traceback.format_exc()}" ) from None - elif raise_if_not_found: + if raise_if_not_found: raise NoAppException(f"Could not import {module_name!r}.") from None - else: - return + return module = sys.modules[module_name] if app_name is None: return find_best_app(module) - else: - return find_app_by_string(module, app_name) + return find_app_by_string(module, app_name) def get_version(ctx, param, value): @@ -242,6 +240,7 @@ def get_version(ctx, param, value): return import werkzeug + from . import __version__ click.echo( @@ -956,7 +955,7 @@ def shell_command() -> None: # is using it. startup = os.environ.get("PYTHONSTARTUP") if startup and os.path.isfile(startup): - with open(startup) as f: + with open(startup, encoding="utf-8") as f: eval(compile(f.read(), startup, "exec"), ctx) ctx.update(current_app.make_shell_context()) diff --git a/src/flask/config.py b/src/flask/config.py index d4fc310f..01b09cad 100644 --- a/src/flask/config.py +++ b/src/flask/config.py @@ -261,7 +261,7 @@ class Config(dict): filename = os.path.join(self.root_path, filename) try: - with open(filename) as f: + with open(filename, encoding="utf-8") as f: obj = load(f) except OSError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): diff --git a/src/flask/ctx.py b/src/flask/ctx.py index ca284494..4c814745 100644 --- a/src/flask/ctx.py +++ b/src/flask/ctx.py @@ -82,8 +82,7 @@ class _AppCtxGlobals: """ if default is _sentinel: return self.__dict__.pop(name) - else: - return self.__dict__.pop(name, default) + return self.__dict__.pop(name, default) def setdefault(self, name: str, default: t.Any = None) -> t.Any: """Get the value of an attribute if it is present, otherwise diff --git a/src/flask/debughelpers.py b/src/flask/debughelpers.py index b0639892..e086b5ef 100644 --- a/src/flask/debughelpers.py +++ b/src/flask/debughelpers.py @@ -106,7 +106,7 @@ def _dump_loader_info(loader) -> t.Generator: for item in value: yield f" - {item}" continue - elif not isinstance(value, (str, int, float, bool)): + if not isinstance(value, (str, int, float, bool)): continue yield f"{key}: {value!r}" diff --git a/src/flask/globals.py b/src/flask/globals.py index 254da42b..b6bf3e55 100644 --- a/src/flask/globals.py +++ b/src/flask/globals.py @@ -5,9 +5,7 @@ from werkzeug.local import LocalProxy if t.TYPE_CHECKING: # pragma: no cover from .app import Flask - from .ctx import _AppCtxGlobals - from .ctx import AppContext - from .ctx import RequestContext + from .ctx import AppContext, RequestContext, _AppCtxGlobals from .sessions import SessionMixin from .wrappers import Request diff --git a/src/flask/helpers.py b/src/flask/helpers.py index 15990d0e..432e0367 100644 --- a/src/flask/helpers.py +++ b/src/flask/helpers.py @@ -20,9 +20,10 @@ from .globals import session from .signals import message_flashed if t.TYPE_CHECKING: # pragma: no cover - from werkzeug.wrappers import Response as BaseResponse - from .wrappers import Response import typing_extensions as te + from werkzeug.wrappers import Response as BaseResponse + + from .wrappers import Response def get_env() -> str: diff --git a/src/flask/scaffold.py b/src/flask/scaffold.py index 1530a11e..75776f4f 100644 --- a/src/flask/scaffold.py +++ b/src/flask/scaffold.py @@ -249,8 +249,7 @@ class Scaffold: """ if self._static_folder is not None: return os.path.join(self.root_path, self._static_folder) - else: - return None + return None @static_folder.setter def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None: @@ -342,8 +341,7 @@ class Scaffold: """ if self.template_folder is not None: return FileSystemLoader(os.path.join(self.root_path, self.template_folder)) - else: - return None + return None def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]: """Open a resource file relative to :attr:`root_path` for @@ -366,7 +364,7 @@ class Scaffold: if mode not in {"r", "rt", "rb"}: raise ValueError("Resources can only be opened for reading.") - return open(os.path.join(self.root_path, resource), mode) + return open(os.path.join(self.root_path, resource), mode, encoding="utf-8") def _method_route( self, @@ -743,8 +741,7 @@ class Scaffold: if issubclass(exc_class, HTTPException): return exc_class, exc_class.code - else: - return exc_class, None + return exc_class, None def _endpoint_from_view_func(view_func: t.Callable) -> str: @@ -824,11 +821,10 @@ def _find_package_path(import_name): search_locations = iter(root_spec.submodule_search_locations) return os.path.dirname(next(search_locations)) # a package (with __init__.py) - elif root_spec.submodule_search_locations: + if root_spec.submodule_search_locations: return os.path.dirname(os.path.dirname(root_spec.origin)) # just a normal module - else: - return os.path.dirname(root_spec.origin) + return os.path.dirname(root_spec.origin) # we were unable to find the `package_path` using PEP 451 loaders loader = pkgutil.get_loader(root_mod_name) diff --git a/src/flask/sessions.py b/src/flask/sessions.py index 02b8cf76..f1b60976 100644 --- a/src/flask/sessions.py +++ b/src/flask/sessions.py @@ -14,6 +14,7 @@ from .json.tag import TaggedJSONSerializer if t.TYPE_CHECKING: # pragma: no cover import typing_extensions as te + from .app import Flask from .wrappers import Request, Response diff --git a/src/flask/views.py b/src/flask/views.py index a82f1912..db8e09fd 100644 --- a/src/flask/views.py +++ b/src/flask/views.py @@ -4,7 +4,6 @@ from . import typing as ft from .globals import current_app from .globals import request - http_method_funcs = frozenset( ["get", "post", "head", "options", "delete", "put", "trace", "patch"] ) diff --git a/src/flask/wrappers.py b/src/flask/wrappers.py index 4b855bfc..39ef1f3f 100644 --- a/src/flask/wrappers.py +++ b/src/flask/wrappers.py @@ -54,8 +54,7 @@ class Request(RequestBase): """Read-only view of the ``MAX_CONTENT_LENGTH`` config key.""" if current_app: return current_app.config["MAX_CONTENT_LENGTH"] - else: - return None + return None @property def endpoint(self) -> t.Optional[str]: diff --git a/tests/conftest.py b/tests/conftest.py index 670acc88..10e24fcf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -95,7 +95,7 @@ def leak_detector(): leaks.append(request_ctx._get_current_object()) request_ctx.pop() - assert leaks == [] + assert not leaks @pytest.fixture(params=(True, False)) diff --git a/tests/test_apps/blueprintapp/__init__.py b/tests/test_apps/blueprintapp/__init__.py index 4b057985..7d71cb3b 100644 --- a/tests/test_apps/blueprintapp/__init__.py +++ b/tests/test_apps/blueprintapp/__init__.py @@ -1,9 +1,11 @@ +from blueprintapp.apps.admin import admin +from blueprintapp.apps.frontend import frontend + from flask import Flask app = Flask(__name__) app.config["DEBUG"] = True -from blueprintapp.apps.admin import admin -from blueprintapp.apps.frontend import frontend + app.register_blueprint(admin) app.register_blueprint(frontend) diff --git a/tests/test_apps/subdomaintestmodule/__init__.py b/tests/test_apps/subdomaintestmodule/__init__.py index 9b83c0d7..b4ce4b16 100644 --- a/tests/test_apps/subdomaintestmodule/__init__.py +++ b/tests/test_apps/subdomaintestmodule/__init__.py @@ -1,4 +1,3 @@ from flask import Module - mod = Module(__name__, "foo", subdomain="foo") diff --git a/tests/test_basic.py b/tests/test_basic.py index d547012a..2b788512 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -20,7 +20,6 @@ from werkzeug.routing import RequestRedirect import flask - require_cpython_gc = pytest.mark.skipif( python_implementation() != "CPython", reason="Requires CPython GC behavior", @@ -191,7 +190,7 @@ def test_url_mapping(app, client): def test_werkzeug_routing(app, client): - from werkzeug.routing import Submount, Rule + from werkzeug.routing import Rule, Submount app.url_map.add( Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")]) @@ -211,7 +210,7 @@ def test_werkzeug_routing(app, client): def test_endpoint_decorator(app, client): - from werkzeug.routing import Submount, Rule + from werkzeug.routing import Rule, Submount app.url_map.add( Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")]) @@ -486,9 +485,9 @@ def test_session_special_types(app, client): client.get("/") s = flask.session assert s["t"] == (1, 2, 3) - assert type(s["b"]) == bytes + assert isinstance(s["b"], bytes) assert s["b"] == b"\xff" - assert type(s["m"]) == flask.Markup + assert isinstance(s["m"], flask.Markup) assert s["m"] == flask.Markup("") assert s["u"] == the_uuid assert s["d"] == now @@ -792,7 +791,7 @@ def test_teardown_request_handler_error(app, client): @app.teardown_request def teardown_request1(exc): - assert type(exc) == ZeroDivisionError + assert isinstance(exc, ZeroDivisionError) called.append(True) # This raises a new error and blows away sys.exc_info(), so we can # test that all teardown_requests get passed the same original @@ -804,7 +803,7 @@ def test_teardown_request_handler_error(app, client): @app.teardown_request def teardown_request2(exc): - assert type(exc) == ZeroDivisionError + assert isinstance(exc, ZeroDivisionError) called.append(True) # This raises a new error and blows away sys.exc_info(), so we can # test that all teardown_requests get passed the same original @@ -1631,7 +1630,7 @@ def test_inject_blueprint_url_defaults(app): app.register_blueprint(bp) - values = dict() + values = {} app.inject_url_defaults("foo.view", values) expected = dict(page="login") assert values == expected diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 1bf130f5..43e1333e 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -712,7 +712,7 @@ def test_request_processing(app, client): app.register_blueprint(bp) - assert evts == [] + assert not evts rv = client.get("/bp") assert rv.data == b"request|after" assert evts == ["before", "after", "teardown"] @@ -750,7 +750,7 @@ def test_app_request_processing(app, client): return "request" # before first request - assert evts == [] + assert not evts # first request resp = client.get("/").data diff --git a/tests/test_cli.py b/tests/test_cli.py index 0d9625b1..03dd19ea 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -227,10 +227,12 @@ def test_locate_app_suppress_raise(test_apps): def test_get_version(test_apps, capsys): - from flask import __version__ as flask_version - from werkzeug import __version__ as werkzeug_version from platform import python_version + from werkzeug import __version__ as werkzeug_version + + from flask import __version__ as flask_version + class MockCtx: resilient_parsing = False color = None diff --git a/tests/test_config.py b/tests/test_config.py index 76c5d272..c3fd1e2f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,7 +6,6 @@ import pytest import flask - # config keys used for the TestConfig TEST_KEY = "foo" SECRET_KEY = "config" diff --git a/tests/test_reqctx.py b/tests/test_reqctx.py index abfacb98..89c7a4bf 100644 --- a/tests/test_reqctx.py +++ b/tests/test_reqctx.py @@ -22,7 +22,7 @@ def test_teardown_on_pop(app): ctx = app.test_request_context() ctx.push() - assert buffer == [] + assert not buffer ctx.pop() assert buffer == [None] @@ -40,7 +40,7 @@ def test_teardown_with_previous_exception(app): pass with app.test_request_context(): - assert buffer == [] + assert not buffer assert buffer == [None] @@ -52,7 +52,7 @@ def test_teardown_with_handled_exception(app): buffer.append(exception) with app.test_request_context(): - assert buffer == [] + assert not buffer try: raise Exception("dummy") except Exception: @@ -234,8 +234,7 @@ def test_session_dynamic_cookie_name(): def get_cookie_name(self, app): if flask.request.url.endswith("dynamic_cookie"): return "dynamic_cookie_name" - else: - return super().get_cookie_name(app) + return super().get_cookie_name(app) class CustomFlask(flask.Flask): session_interface = PathAwareSessionInterface()