pylint issues resolved

Ran tests, and black afterwards. Updated changes.rst and included pre-commit hooks as required.  Ran isort on imports.
This commit is contained in:
Mark Mayo 2022-10-13 18:15:15 +13:00
parent 3dc6db9d0c
commit dde76ea960
32 changed files with 114 additions and 132 deletions

View file

@ -7,7 +7,7 @@ Unreleased
Version 2.2.3
-------------
Unreleased
- tidy up of pylint issues across several files
Version 2.2.2

View file

@ -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

View file

@ -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("/<any(xhr, jquery, fetch):js>")

View file

@ -1,5 +1,4 @@
import pytest
from js_example import app

View file

@ -1,4 +1,5 @@
import pytest
from flask import template_rendered

View file

@ -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")

View file

@ -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__)

View file

@ -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():

View file

@ -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:

View file

@ -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

View file

@ -1,5 +1,4 @@
import pytest
from flaskr.db import get_db

View file

@ -1,7 +1,6 @@
import sqlite3
import pytest
from flaskr.db import get_db

View file

@ -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(

View file

@ -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:

View file

@ -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())

View file

@ -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):

View file

@ -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

View file

@ -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}"

View file

@ -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

View file

@ -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:

View file

@ -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)

View file

@ -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

View file

@ -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"]
)

View file

@ -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]:

View file

@ -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))

View file

@ -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)

View file

@ -1,4 +1,3 @@
from flask import Module
mod = Module(__name__, "foo", subdomain="foo")

View file

@ -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("<html>")
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

View file

@ -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

View file

@ -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

View file

@ -6,7 +6,6 @@ import pytest
import flask
# config keys used for the TestConfig
TEST_KEY = "foo"
SECRET_KEY = "config"

View file

@ -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()