server: format code to flake8

This commit is contained in:
Shyam Sunder 2020-06-05 10:02:18 -04:00
parent c5358f7f83
commit ea623449e7
33 changed files with 27 additions and 78 deletions

View file

@ -1,6 +1,5 @@
# Linter configs
.pylintrc
mypy.ini
setup.cfg
# Python requirements files
requirements.txt

View file

@ -1,37 +0,0 @@
[basic]
function-rgx=^_?[a-z_][a-z0-9_]{2,}$|^test_
method-rgx=^[a-z_][a-z0-9_]{2,}$|^test_
const-rgx=^[A-Z_]+$|^_[a-zA-Z_]*$
good-names=ex,_,logger,i
[variables]
dummy-variables-rgx=_|dummy
[format]
max-line-length=79
[messages control]
reports=no
disable=
# we're not java
missing-docstring,
broad-except,
# covered better by pycodestyle
bad-continuation,
# we're adults
redefined-builtin,
duplicate-code,
too-many-return-statements,
too-many-arguments,
# plain stupid
no-self-use,
too-few-public-methods
[typecheck]
generated-members=add|add_all
[similarities]
min-similarity-lines=5

View file

@ -1,3 +1,9 @@
[flake8]
filename = szurubooru/
exclude = __pycache__
ignore = F401, W503, W504
max-line-length = 79
[mypy]
ignore_missing_imports = True
follow_imports = skip

View file

@ -10,7 +10,7 @@ _cache_result = None # type: Optional[int]
def _get_disk_usage() -> int:
global _cache_time, _cache_result # pylint: disable=global-statement
global _cache_time, _cache_result
threshold = timedelta(hours=48)
now = datetime.utcnow()
if _cache_time and _cache_time > now - threshold:

View file

@ -56,4 +56,4 @@ def _read_config() -> Dict:
return ret
config = _read_config() # pylint: disable=invalid-name
config = _read_config()

View file

@ -4,7 +4,7 @@ import sqlalchemy as sa
import sqlalchemy.orm
from szurubooru import config
# pylint: disable=invalid-name
_data = threading.local()
_engine = sa.create_engine(config.config['database']) # type: Any
_sessionmaker = sa.orm.sessionmaker(bind=_engine, autoflush=False) # type: Any

View file

@ -10,7 +10,6 @@ import sqlalchemy.orm.exc
from szurubooru import config, db, errors, rest
from szurubooru.func.posts import update_all_post_signatures
from szurubooru.func.file_uploads import purge_old_uploads
# pylint: disable=unused-import
from szurubooru import api, middleware
@ -147,4 +146,4 @@ def create_app() -> Callable[[Any, Any], Any]:
return rest.application
app = create_app() # pylint: disable=invalid-name
app = create_app()

View file

@ -54,7 +54,7 @@ def create_password() -> str:
'n': list('0123456789'),
}
pattern = 'cvcvnncvcv'
return ''.join(random.choice(alphabet[l]) for l in list(pattern))
return ''.join(random.choice(alphabet[type]) for type in list(pattern))
def is_valid_password(user: model.User, password: str) -> bool:

View file

@ -7,7 +7,7 @@ import numpy as np
from PIL import Image
from szurubooru import config, errors
# pylint: disable=invalid-name
logger = logging.getLogger(__name__)
# Math based on paper from H. Chi Wong, Marshall Bern and David Goldberg
@ -242,7 +242,6 @@ def pack_signature(signature: NpMatrix) -> bytes:
This is then converted into a more packed array consisting of
uint32 elements (for SIG_CHUNK_BITS = 32).
'''
base = 2 * N_LEVELS + 1
coding_vector = np.flipud(SIG_BASE**np.arange(SIG_CHUNK_WIDTH))
return np.array([
np.dot(x, coding_vector) for x in
@ -256,7 +255,6 @@ def unpack_signature(packed: bytes) -> NpMatrix:
Functions as an inverse transformation of pack_signature()
'''
base = 2 * N_LEVELS + 1
return np.ravel(np.array([
[
int(digit) - N_LEVELS for digit in

View file

@ -53,7 +53,8 @@ def is_video(mime_type: str) -> bool:
def is_image(mime_type: str) -> bool:
return mime_type.lower() in ('image/jpeg', 'image/png', 'image/gif', 'image/webp')
return mime_type.lower() in (
'image/jpeg', 'image/png', 'image/gif', 'image/webp')
def is_animated_gif(content: bytes) -> bool:

View file

@ -49,6 +49,6 @@ def _youtube_dl_wrapper(url: str) -> bytes:
except YoutubeDLError as ex:
raise errors.ThirdPartyError(
'Error downloading video %s (%s)' % (url, ex))
except FileNotFoundError as ex:
except FileNotFoundError:
raise errors.ThirdPartyError(
'Error downloading video %s (file could not be saved)' % (url))

View file

@ -529,7 +529,7 @@ def update_all_post_signatures() -> None:
.filter(
(model.Post.type == model.Post.TYPE_IMAGE) |
(model.Post.type == model.Post.TYPE_ANIMATION))
.filter(model.Post.signature == None)
.filter(model.Post.signature == None) # noqa: E711
.order_by(model.Post.post_id.asc())
.all())
for post in posts_to_hash:

View file

@ -61,7 +61,6 @@ def get_post_snapshot(post: model.Post) -> Dict[str, Any]:
_snapshot_factories = {
# lambdas allow mocking target functions in the tests
# pylint: disable=unnecessary-lambda
'tag_category': lambda entity: get_tag_category_snapshot(entity),
'tag': lambda entity: get_tag_snapshot(entity),
'post': lambda entity: get_post_snapshot(entity),
@ -108,7 +107,6 @@ def create(entity: model.Base, auth_user: Optional[model.User]) -> None:
db.session.add(snapshot)
# pylint: disable=protected-access
def modify(entity: model.Base, auth_user: Optional[model.User]) -> None:
assert entity

View file

@ -84,7 +84,7 @@ def is_valid_email(email: Optional[str]) -> bool:
return not email or re.match(r'^[^@]*@[^@]*\.[^@]*$', email) is not None
class dotdict(dict): # pylint: disable=invalid-name
class dotdict(dict):
''' dot.notation access to dictionary attributes. '''
def __getattr__(self, attr: str) -> Any:
return self.get(attr)

View file

@ -10,8 +10,8 @@ from time import sleep
dir_to_self = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(dir_to_self, *[os.pardir] * 2))
import szurubooru.model.base
import szurubooru.config
import szurubooru.model.base # noqa: E402
import szurubooru.config # noqa: E402
alembic_config = alembic.context.config
logging.config.fileConfig(alembic_config.config_file_name)

View file

@ -36,7 +36,7 @@ def downgrade():
entry.name)
if match:
post_id = int(match.group('name'))
security_hash = match.group('hash')
security_hash = match.group('hash') # noqa: F841
ext = match.group('ext')
new_name = '%s.%s' % (post_id, ext)
new_path = os.path.join(os.path.dirname(entry.path), new_name)

View file

@ -29,7 +29,6 @@ def upgrade():
for row in conn.execute(posts.select()):
newflag = ','.join(row.oldflags) if row.oldflags else ''
conn.execute(
# pylint: disable=no-value-for-parameter
posts.update().where(
posts.c.id == row.id
).values(
@ -53,7 +52,6 @@ def downgrade():
for row in conn.execute(posts.select()):
newflag = [x for x in row.oldflags.split(',') if x]
conn.execute(
# pylint: disable=no-value-for-parameter
posts.update().where(
posts.c.id == row.id
).values(

View file

@ -1,4 +1,4 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base() # pylint: disable=invalid-name
Base = declarative_base()

View file

@ -1,7 +1,7 @@
from typing import Optional, Callable, Type, Dict
error_handlers = {} # pylint: disable=invalid-name
error_handlers = {}
class BaseHttpError(RuntimeError):

View file

@ -2,7 +2,6 @@ from typing import List, Callable
from szurubooru.rest.context import Context
# pylint: disable=invalid-name
pre_hooks = [] # type: List[Callable[[Context], None]]
post_hooks = [] # type: List[Callable[[Context], None]]

View file

@ -3,7 +3,6 @@ from collections import defaultdict
from szurubooru.rest.context import Context, Response
# pylint: disable=invalid-name
RouteHandler = Callable[[Context, Dict[str, str]], Response]
routes = defaultdict(dict) # type: Dict[str, Dict[str, RouteHandler]]

View file

@ -80,8 +80,7 @@ def _user_filter(
assert criterion
if isinstance(criterion, criteria.PlainCriterion) \
and not criterion.value:
# pylint: disable=singleton-comparison
expr = model.Post.user_id == None
expr = model.Post.user_id == None # noqa: E711
if negated:
expr = ~expr
return query.filter(expr)

View file

@ -17,7 +17,7 @@ def unescape(text: str, make_wildcards_special: bool = False) -> str:
while i < len(text):
if text[i] == '\\':
try:
char = text[i+1]
char = text[i + 1]
i += 1
except IndexError:
raise errors.SearchError(

View file

@ -1,4 +1,3 @@
# pylint: disable=redefined-outer-name
import contextlib
import os
import random
@ -39,7 +38,7 @@ def query_logger(pytestconfig):
@pytest.yield_fixture(scope='function', autouse=True)
def session(query_logger, postgresql_db): # pylint: disable=unused-argument
def session(query_logger, postgresql_db):
db.session = postgresql_db.session
postgresql_db.create_table(*model.Base.metadata.sorted_tables)
try:
@ -141,7 +140,6 @@ def tag_factory():
@pytest.fixture
def post_factory():
# pylint: disable=invalid-name
def factory(
id=None,
safety=model.Post.SAFETY_SAFE,

View file

@ -4,7 +4,7 @@ from szurubooru import errors
from szurubooru.func import util
dt = datetime # pylint: disable=invalid-name
dt = datetime
def test_parsing_empty_date_time():

View file

@ -50,7 +50,6 @@ def test_saving_post(post_factory, user_factory, tag_factory):
assert len(related_post2.relations) == 0
# pylint: disable=too-many-statements
def test_cascade_deletions(
post_factory, user_factory, tag_factory, comment_factory):
user = user_factory()

View file

@ -111,7 +111,6 @@ def test_disliked_post_count(user_factory, post_factory):
assert user1.disliked_post_count == 1
# pylint: disable=too-many-statements
def test_cascade_deletions(post_factory, user_factory, comment_factory):
user = user_factory()

View file

@ -1,4 +1,3 @@
# pylint: disable=unexpected-keyword-arg
import unittest.mock
import pytest
from szurubooru import rest, errors

View file

@ -1,4 +1,3 @@
# pylint: disable=redefined-outer-name
from datetime import datetime
import pytest
from szurubooru import db, search

View file

@ -1,4 +1,3 @@
# pylint: disable=redefined-outer-name
from datetime import datetime
import pytest
from szurubooru import db, errors, search

View file

@ -1,4 +1,3 @@
# pylint: disable=redefined-outer-name
from datetime import datetime
import pytest
from szurubooru import db, model, errors, search

View file

@ -1,4 +1,3 @@
# pylint: disable=redefined-outer-name
from datetime import datetime
import pytest
from szurubooru import db, errors, search

View file

@ -1,4 +1,3 @@
# pylint: disable=redefined-outer-name
from datetime import datetime
import pytest
from szurubooru import db, errors, search