Skip to content

Commit

Permalink
refactor: More style changes (to comply with mypy)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan Christie committed Dec 7, 2023
1 parent cd0d520 commit a78469d
Show file tree
Hide file tree
Showing 10 changed files with 38 additions and 36 deletions.
8 changes: 1 addition & 7 deletions api/security.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# pylint: skip-file
import logging
import os
import time

from pathlib import Path
from typing import Any

from wsgiref.util import FileWrapper
from django.http import Http404
Expand Down Expand Up @@ -102,12 +102,6 @@ def get_conn():


class ISpyBSafeQuerySet(viewsets.ReadOnlyModelViewSet):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.request = None
self.filter_permissions = None
self.queryset = None

def get_queryset(self):
"""
Optionally restricts the returned purchases to a given proposals
Expand Down
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
exclude_patterns = [] # type: ignore


# -- Options for HTML output -------------------------------------------------
Expand Down
10 changes: 5 additions & 5 deletions fragalysis/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,11 @@
if os.environ.get("BUILD_XCDB") == 'yes':
DATABASES["xchem_db"] = {
"ENGINE": 'django.db.backends.postgresql',
"NAME": os.environ.get("XCHEM_NAME"),
"USER": os.environ.get("XCHEM_USER"),
"PASSWORD": os.environ.get("XCHEM_PASSWORD"),
"HOST": os.environ.get("XCHEM_HOST"),
"PORT": os.environ.get("XCHEM_PORT"),
"NAME": os.environ.get("XCHEM_NAME", ""),
"USER": os.environ.get("XCHEM_USER", ""),
"PASSWORD": os.environ.get("XCHEM_PASSWORD", ""),
"HOST": os.environ.get("XCHEM_HOST", ""),
"PORT": os.environ.get("XCHEM_PORT", ""),
}

if CHEMCENTRAL_DB_NAME != "UNKOWN":
Expand Down
12 changes: 6 additions & 6 deletions viewer/cset_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,13 @@

def dataType(a_str: str) -> str:
lean_str = a_str.strip()
if len(lean_str) == 0:
if not lean_str:
return 'BLANK'

try:
t = ast.literal_eval(lean_str)

except ValueError:
return 'TEXT'
except SyntaxError:
except (ValueError, SyntaxError):
return 'TEXT'

else:
if type(t) in [int, int, float, bool]:
if t in [
Expand All @@ -72,6 +69,9 @@ def dataType(a_str: str) -> str:
return 'INT'
if type(t) is float:
return 'FLOAT'

# Can't get here?
assert False
else:
return 'TEXT'

Expand Down
17 changes: 10 additions & 7 deletions viewer/discourse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
discourse.py Functions for to send and retrieve posts to/fraom the discourse platform.
"""
import os
from typing import Tuple

from pydiscourse import DiscourseClient
from django.conf import settings
from viewer.models import DiscourseCategory, DiscourseTopic
Expand All @@ -10,15 +12,16 @@
logger = logging.getLogger(__name__)


def get_user(client, username):
"""Call discourse API users to retreive user by username."""
def get_user(client, username) -> Tuple[bool, str, int]:
"""Call discourse API users to retrieve user by username."""
logger.info('+ discourse.get_user')
error = False
error_message = ''
user = 0

error: bool = False
error_message: str = ''
user: int = 0

try:
user = client.user(username)
user_record = client.user(username)
except Exception as e:
# User is not known in Discourse or there is a failure accessing Discourse.
logger.error('discourse.get_user', exc_info=e)
Expand All @@ -33,7 +36,7 @@ def get_user(client, username):
else:
error_message = 'Please check Discourse Host parameter for Fragalysis'
else:
user = user['id']
user = user_record['id']

logger.info('- discourse.get_user')
return error, error_message, user
Expand Down
2 changes: 1 addition & 1 deletion viewer/migrations/0018_merge_20231109_1252.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ class Migration(migrations.Migration):
('viewer', '0017_alter_experimentupload_message'),
]

operations = []
operations = [] # type: ignore
5 changes: 3 additions & 2 deletions viewer/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from dataclasses import dataclass
import uuid
import logging
from typing import List

from django.contrib.auth.models import User
from django.db import models
Expand Down Expand Up @@ -457,13 +458,13 @@ def get_vectors(
cmpd_id=None,
vector_type=None,
number=None,
):
) -> List[Vector3d]:
"""Get the vectors for a given molecule
:param mols: the Django molecules to get them from
:return: None
"""
result = []
result: List[Vector3d] = []
# pk checks and later continure statements are doing filtering
# - as this is not going through the usual django_filter
# machinery, it needs a different approach
Expand Down
11 changes: 7 additions & 4 deletions viewer/squonk_job_file_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""
import urllib.parse
import os
from typing import Dict, List, Tuple

from django.conf import settings
from rest_framework import status
Expand Down Expand Up @@ -109,7 +110,9 @@ def process_file_transfer(auth_token, job_transfer_id):
raise RuntimeError(msg)


def validate_file_transfer_files(request):
def validate_file_transfer_files(
request,
) -> Tuple[Dict[str, str], List[SiteObservation], List[ComputedMolecule]]:
"""Check the request and return a list of proteins and/or computed molecule objects
Args:
Expand All @@ -119,9 +122,9 @@ def validate_file_transfer_files(request):
list of validated proteins (SiteObservation)
list of validated computed molecules (ComputedMolecule)
"""
error = {}
proteins = []
compounds = []
error: Dict[str, str] = {}
proteins: List[SiteObservation] = []
compounds: List[ComputedMolecule] = []

if request.data['proteins']:
# Get first part of protein code
Expand Down
3 changes: 2 additions & 1 deletion viewer/target_set_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""
import logging
import sys
from typing import Any, Dict

# import json
import os
Expand Down Expand Up @@ -801,7 +802,7 @@ def validate_target(new_data_folder, target_name, proposal_ref):
# Don't need
del proposal_ref

validate_dict = {'Location': [], 'Error': [], 'Line number': []}
validate_dict: Dict[str, Any] = {'Location': [], 'Error': [], 'Line number': []}

# Check if there is any data to process
target_path = os.path.join(new_data_folder, target_name)
Expand Down
4 changes: 2 additions & 2 deletions viewer/tests/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
from viewer.models import QuatAssembly


test_mpro_v1 = Path(__file__).absolute().parent.joinpath("Mpro-v1-zero.tgz")
test_mpro_v2 = Path(__file__).absolute().parent.joinpath("Mpro-v2-zero.tgz")
test_mpro_v1 = str(Path(__file__).absolute().parent.joinpath("Mpro-v1-zero.tgz"))
test_mpro_v2 = str(Path(__file__).absolute().parent.joinpath("Mpro-v2-zero.tgz"))


class LoaderTests(TestCase):
Expand Down

0 comments on commit a78469d

Please sign in to comment.