server: format code to flake8
This commit is contained in:
parent
c5358f7f83
commit
ea623449e7
33 changed files with 27 additions and 78 deletions
|
@ -1,6 +1,5 @@
|
||||||
# Linter configs
|
# Linter configs
|
||||||
.pylintrc
|
setup.cfg
|
||||||
mypy.ini
|
|
||||||
|
|
||||||
# Python requirements files
|
# Python requirements files
|
||||||
requirements.txt
|
requirements.txt
|
||||||
|
|
|
@ -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
|
|
|
@ -1,3 +1,9 @@
|
||||||
|
[flake8]
|
||||||
|
filename = szurubooru/
|
||||||
|
exclude = __pycache__
|
||||||
|
ignore = F401, W503, W504
|
||||||
|
max-line-length = 79
|
||||||
|
|
||||||
[mypy]
|
[mypy]
|
||||||
ignore_missing_imports = True
|
ignore_missing_imports = True
|
||||||
follow_imports = skip
|
follow_imports = skip
|
|
@ -10,7 +10,7 @@ _cache_result = None # type: Optional[int]
|
||||||
|
|
||||||
|
|
||||||
def _get_disk_usage() -> int:
|
def _get_disk_usage() -> int:
|
||||||
global _cache_time, _cache_result # pylint: disable=global-statement
|
global _cache_time, _cache_result
|
||||||
threshold = timedelta(hours=48)
|
threshold = timedelta(hours=48)
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
if _cache_time and _cache_time > now - threshold:
|
if _cache_time and _cache_time > now - threshold:
|
||||||
|
|
|
@ -56,4 +56,4 @@ def _read_config() -> Dict:
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
config = _read_config() # pylint: disable=invalid-name
|
config = _read_config()
|
||||||
|
|
|
@ -4,7 +4,7 @@ import sqlalchemy as sa
|
||||||
import sqlalchemy.orm
|
import sqlalchemy.orm
|
||||||
from szurubooru import config
|
from szurubooru import config
|
||||||
|
|
||||||
# pylint: disable=invalid-name
|
|
||||||
_data = threading.local()
|
_data = threading.local()
|
||||||
_engine = sa.create_engine(config.config['database']) # type: Any
|
_engine = sa.create_engine(config.config['database']) # type: Any
|
||||||
_sessionmaker = sa.orm.sessionmaker(bind=_engine, autoflush=False) # type: Any
|
_sessionmaker = sa.orm.sessionmaker(bind=_engine, autoflush=False) # type: Any
|
||||||
|
|
|
@ -10,7 +10,6 @@ import sqlalchemy.orm.exc
|
||||||
from szurubooru import config, db, errors, rest
|
from szurubooru import config, db, errors, rest
|
||||||
from szurubooru.func.posts import update_all_post_signatures
|
from szurubooru.func.posts import update_all_post_signatures
|
||||||
from szurubooru.func.file_uploads import purge_old_uploads
|
from szurubooru.func.file_uploads import purge_old_uploads
|
||||||
# pylint: disable=unused-import
|
|
||||||
from szurubooru import api, middleware
|
from szurubooru import api, middleware
|
||||||
|
|
||||||
|
|
||||||
|
@ -147,4 +146,4 @@ def create_app() -> Callable[[Any, Any], Any]:
|
||||||
return rest.application
|
return rest.application
|
||||||
|
|
||||||
|
|
||||||
app = create_app() # pylint: disable=invalid-name
|
app = create_app()
|
||||||
|
|
|
@ -54,7 +54,7 @@ def create_password() -> str:
|
||||||
'n': list('0123456789'),
|
'n': list('0123456789'),
|
||||||
}
|
}
|
||||||
pattern = 'cvcvnncvcv'
|
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:
|
def is_valid_password(user: model.User, password: str) -> bool:
|
||||||
|
|
|
@ -7,7 +7,7 @@ import numpy as np
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from szurubooru import config, errors
|
from szurubooru import config, errors
|
||||||
|
|
||||||
# pylint: disable=invalid-name
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Math based on paper from H. Chi Wong, Marshall Bern and David Goldberg
|
# 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
|
This is then converted into a more packed array consisting of
|
||||||
uint32 elements (for SIG_CHUNK_BITS = 32).
|
uint32 elements (for SIG_CHUNK_BITS = 32).
|
||||||
'''
|
'''
|
||||||
base = 2 * N_LEVELS + 1
|
|
||||||
coding_vector = np.flipud(SIG_BASE**np.arange(SIG_CHUNK_WIDTH))
|
coding_vector = np.flipud(SIG_BASE**np.arange(SIG_CHUNK_WIDTH))
|
||||||
return np.array([
|
return np.array([
|
||||||
np.dot(x, coding_vector) for x in
|
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()
|
Functions as an inverse transformation of pack_signature()
|
||||||
'''
|
'''
|
||||||
base = 2 * N_LEVELS + 1
|
|
||||||
return np.ravel(np.array([
|
return np.ravel(np.array([
|
||||||
[
|
[
|
||||||
int(digit) - N_LEVELS for digit in
|
int(digit) - N_LEVELS for digit in
|
||||||
|
|
|
@ -53,7 +53,8 @@ def is_video(mime_type: str) -> bool:
|
||||||
|
|
||||||
|
|
||||||
def is_image(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:
|
def is_animated_gif(content: bytes) -> bool:
|
||||||
|
|
|
@ -49,6 +49,6 @@ def _youtube_dl_wrapper(url: str) -> bytes:
|
||||||
except YoutubeDLError as ex:
|
except YoutubeDLError as ex:
|
||||||
raise errors.ThirdPartyError(
|
raise errors.ThirdPartyError(
|
||||||
'Error downloading video %s (%s)' % (url, ex))
|
'Error downloading video %s (%s)' % (url, ex))
|
||||||
except FileNotFoundError as ex:
|
except FileNotFoundError:
|
||||||
raise errors.ThirdPartyError(
|
raise errors.ThirdPartyError(
|
||||||
'Error downloading video %s (file could not be saved)' % (url))
|
'Error downloading video %s (file could not be saved)' % (url))
|
||||||
|
|
|
@ -529,7 +529,7 @@ def update_all_post_signatures() -> None:
|
||||||
.filter(
|
.filter(
|
||||||
(model.Post.type == model.Post.TYPE_IMAGE) |
|
(model.Post.type == model.Post.TYPE_IMAGE) |
|
||||||
(model.Post.type == model.Post.TYPE_ANIMATION))
|
(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())
|
.order_by(model.Post.post_id.asc())
|
||||||
.all())
|
.all())
|
||||||
for post in posts_to_hash:
|
for post in posts_to_hash:
|
||||||
|
|
|
@ -61,7 +61,6 @@ def get_post_snapshot(post: model.Post) -> Dict[str, Any]:
|
||||||
|
|
||||||
_snapshot_factories = {
|
_snapshot_factories = {
|
||||||
# lambdas allow mocking target functions in the tests
|
# lambdas allow mocking target functions in the tests
|
||||||
# pylint: disable=unnecessary-lambda
|
|
||||||
'tag_category': lambda entity: get_tag_category_snapshot(entity),
|
'tag_category': lambda entity: get_tag_category_snapshot(entity),
|
||||||
'tag': lambda entity: get_tag_snapshot(entity),
|
'tag': lambda entity: get_tag_snapshot(entity),
|
||||||
'post': lambda entity: get_post_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)
|
db.session.add(snapshot)
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=protected-access
|
|
||||||
def modify(entity: model.Base, auth_user: Optional[model.User]) -> None:
|
def modify(entity: model.Base, auth_user: Optional[model.User]) -> None:
|
||||||
assert entity
|
assert entity
|
||||||
|
|
||||||
|
|
|
@ -84,7 +84,7 @@ def is_valid_email(email: Optional[str]) -> bool:
|
||||||
return not email or re.match(r'^[^@]*@[^@]*\.[^@]*$', email) is not None
|
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. '''
|
''' dot.notation access to dictionary attributes. '''
|
||||||
def __getattr__(self, attr: str) -> Any:
|
def __getattr__(self, attr: str) -> Any:
|
||||||
return self.get(attr)
|
return self.get(attr)
|
||||||
|
|
|
@ -10,8 +10,8 @@ from time import sleep
|
||||||
dir_to_self = os.path.dirname(os.path.realpath(__file__))
|
dir_to_self = os.path.dirname(os.path.realpath(__file__))
|
||||||
sys.path.append(os.path.join(dir_to_self, *[os.pardir] * 2))
|
sys.path.append(os.path.join(dir_to_self, *[os.pardir] * 2))
|
||||||
|
|
||||||
import szurubooru.model.base
|
import szurubooru.model.base # noqa: E402
|
||||||
import szurubooru.config
|
import szurubooru.config # noqa: E402
|
||||||
|
|
||||||
alembic_config = alembic.context.config
|
alembic_config = alembic.context.config
|
||||||
logging.config.fileConfig(alembic_config.config_file_name)
|
logging.config.fileConfig(alembic_config.config_file_name)
|
||||||
|
|
|
@ -36,7 +36,7 @@ def downgrade():
|
||||||
entry.name)
|
entry.name)
|
||||||
if match:
|
if match:
|
||||||
post_id = int(match.group('name'))
|
post_id = int(match.group('name'))
|
||||||
security_hash = match.group('hash')
|
security_hash = match.group('hash') # noqa: F841
|
||||||
ext = match.group('ext')
|
ext = match.group('ext')
|
||||||
new_name = '%s.%s' % (post_id, ext)
|
new_name = '%s.%s' % (post_id, ext)
|
||||||
new_path = os.path.join(os.path.dirname(entry.path), new_name)
|
new_path = os.path.join(os.path.dirname(entry.path), new_name)
|
||||||
|
|
|
@ -29,7 +29,6 @@ def upgrade():
|
||||||
for row in conn.execute(posts.select()):
|
for row in conn.execute(posts.select()):
|
||||||
newflag = ','.join(row.oldflags) if row.oldflags else ''
|
newflag = ','.join(row.oldflags) if row.oldflags else ''
|
||||||
conn.execute(
|
conn.execute(
|
||||||
# pylint: disable=no-value-for-parameter
|
|
||||||
posts.update().where(
|
posts.update().where(
|
||||||
posts.c.id == row.id
|
posts.c.id == row.id
|
||||||
).values(
|
).values(
|
||||||
|
@ -53,7 +52,6 @@ def downgrade():
|
||||||
for row in conn.execute(posts.select()):
|
for row in conn.execute(posts.select()):
|
||||||
newflag = [x for x in row.oldflags.split(',') if x]
|
newflag = [x for x in row.oldflags.split(',') if x]
|
||||||
conn.execute(
|
conn.execute(
|
||||||
# pylint: disable=no-value-for-parameter
|
|
||||||
posts.update().where(
|
posts.update().where(
|
||||||
posts.c.id == row.id
|
posts.c.id == row.id
|
||||||
).values(
|
).values(
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
|
||||||
|
|
||||||
Base = declarative_base() # pylint: disable=invalid-name
|
Base = declarative_base()
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import Optional, Callable, Type, Dict
|
from typing import Optional, Callable, Type, Dict
|
||||||
|
|
||||||
|
|
||||||
error_handlers = {} # pylint: disable=invalid-name
|
error_handlers = {}
|
||||||
|
|
||||||
|
|
||||||
class BaseHttpError(RuntimeError):
|
class BaseHttpError(RuntimeError):
|
||||||
|
|
|
@ -2,7 +2,6 @@ from typing import List, Callable
|
||||||
from szurubooru.rest.context import Context
|
from szurubooru.rest.context import Context
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=invalid-name
|
|
||||||
pre_hooks = [] # type: List[Callable[[Context], None]]
|
pre_hooks = [] # type: List[Callable[[Context], None]]
|
||||||
post_hooks = [] # type: List[Callable[[Context], None]]
|
post_hooks = [] # type: List[Callable[[Context], None]]
|
||||||
|
|
||||||
|
|
|
@ -3,7 +3,6 @@ from collections import defaultdict
|
||||||
from szurubooru.rest.context import Context, Response
|
from szurubooru.rest.context import Context, Response
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=invalid-name
|
|
||||||
RouteHandler = Callable[[Context, Dict[str, str]], Response]
|
RouteHandler = Callable[[Context, Dict[str, str]], Response]
|
||||||
routes = defaultdict(dict) # type: Dict[str, Dict[str, RouteHandler]]
|
routes = defaultdict(dict) # type: Dict[str, Dict[str, RouteHandler]]
|
||||||
|
|
||||||
|
|
|
@ -80,8 +80,7 @@ def _user_filter(
|
||||||
assert criterion
|
assert criterion
|
||||||
if isinstance(criterion, criteria.PlainCriterion) \
|
if isinstance(criterion, criteria.PlainCriterion) \
|
||||||
and not criterion.value:
|
and not criterion.value:
|
||||||
# pylint: disable=singleton-comparison
|
expr = model.Post.user_id == None # noqa: E711
|
||||||
expr = model.Post.user_id == None
|
|
||||||
if negated:
|
if negated:
|
||||||
expr = ~expr
|
expr = ~expr
|
||||||
return query.filter(expr)
|
return query.filter(expr)
|
||||||
|
|
|
@ -17,7 +17,7 @@ def unescape(text: str, make_wildcards_special: bool = False) -> str:
|
||||||
while i < len(text):
|
while i < len(text):
|
||||||
if text[i] == '\\':
|
if text[i] == '\\':
|
||||||
try:
|
try:
|
||||||
char = text[i+1]
|
char = text[i + 1]
|
||||||
i += 1
|
i += 1
|
||||||
except IndexError:
|
except IndexError:
|
||||||
raise errors.SearchError(
|
raise errors.SearchError(
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
import contextlib
|
import contextlib
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
|
@ -39,7 +38,7 @@ def query_logger(pytestconfig):
|
||||||
|
|
||||||
|
|
||||||
@pytest.yield_fixture(scope='function', autouse=True)
|
@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
|
db.session = postgresql_db.session
|
||||||
postgresql_db.create_table(*model.Base.metadata.sorted_tables)
|
postgresql_db.create_table(*model.Base.metadata.sorted_tables)
|
||||||
try:
|
try:
|
||||||
|
@ -141,7 +140,6 @@ def tag_factory():
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def post_factory():
|
def post_factory():
|
||||||
# pylint: disable=invalid-name
|
|
||||||
def factory(
|
def factory(
|
||||||
id=None,
|
id=None,
|
||||||
safety=model.Post.SAFETY_SAFE,
|
safety=model.Post.SAFETY_SAFE,
|
||||||
|
|
|
@ -4,7 +4,7 @@ from szurubooru import errors
|
||||||
from szurubooru.func import util
|
from szurubooru.func import util
|
||||||
|
|
||||||
|
|
||||||
dt = datetime # pylint: disable=invalid-name
|
dt = datetime
|
||||||
|
|
||||||
|
|
||||||
def test_parsing_empty_date_time():
|
def test_parsing_empty_date_time():
|
||||||
|
|
|
@ -50,7 +50,6 @@ def test_saving_post(post_factory, user_factory, tag_factory):
|
||||||
assert len(related_post2.relations) == 0
|
assert len(related_post2.relations) == 0
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=too-many-statements
|
|
||||||
def test_cascade_deletions(
|
def test_cascade_deletions(
|
||||||
post_factory, user_factory, tag_factory, comment_factory):
|
post_factory, user_factory, tag_factory, comment_factory):
|
||||||
user = user_factory()
|
user = user_factory()
|
||||||
|
|
|
@ -111,7 +111,6 @@ def test_disliked_post_count(user_factory, post_factory):
|
||||||
assert user1.disliked_post_count == 1
|
assert user1.disliked_post_count == 1
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=too-many-statements
|
|
||||||
def test_cascade_deletions(post_factory, user_factory, comment_factory):
|
def test_cascade_deletions(post_factory, user_factory, comment_factory):
|
||||||
user = user_factory()
|
user = user_factory()
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=unexpected-keyword-arg
|
|
||||||
import unittest.mock
|
import unittest.mock
|
||||||
import pytest
|
import pytest
|
||||||
from szurubooru import rest, errors
|
from szurubooru import rest, errors
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import pytest
|
import pytest
|
||||||
from szurubooru import db, search
|
from szurubooru import db, search
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import pytest
|
import pytest
|
||||||
from szurubooru import db, errors, search
|
from szurubooru import db, errors, search
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import pytest
|
import pytest
|
||||||
from szurubooru import db, model, errors, search
|
from szurubooru import db, model, errors, search
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import pytest
|
import pytest
|
||||||
from szurubooru import db, errors, search
|
from szurubooru import db, errors, search
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
# pylint: disable=redefined-outer-name
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import pytest
|
import pytest
|
||||||
from szurubooru import db, errors, search
|
from szurubooru import db, errors, search
|
||||||
|
|
Loading…
Reference in a new issue