Skip to content

Commit

Permalink
Temp: Use pylint
Browse files Browse the repository at this point in the history
  • Loading branch information
CasperWA committed Oct 21, 2022
1 parent 91cec03 commit 038c5fe
Show file tree
Hide file tree
Showing 19 changed files with 146 additions and 107 deletions.
7 changes: 5 additions & 2 deletions .github/mongo/load_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
client = MongoClient("mongodb://localhost:27017")
collection = client["aiida_optimade"]["structures"]

with open(Path(__file__).parent.joinpath("test_structures_mongo.json")) as handle:
data = bson.json_util.loads(handle.read())
data = bson.json_util.loads(
Path(__file__)
.parent.joinpath("test_structures_mongo.json")
.read_text(encoding="utf8")
)

try:
print(f"Inserting {len(data)} structures into {collection.full_name}")
Expand Down
23 changes: 22 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ repos:
rev: 22.10.0
hooks:
- id: black
name: Blacken

- repo: local
hooks:
Expand All @@ -42,3 +41,25 @@ repos:
.codecov.yml
)$
language: system
- id: pylint
name: pylint
entry: pylint
args:
- --rcfile=pyproject.toml
- --extension-pkg-whitelist='pydantic'
language: python
types: [python]
require_serial: true
files: ^.*$
exclude: ^tests/.*$
- id: pylint-tests
name: pylint - tests
entry: pylint
args:
- --rcfile=pyproject.toml
- --extension-pkg-whitelist='pydantic'
- --disable=import-outside-toplevel,redefined-outer-name
language: python
types: [python]
require_serial: true
files: ^tests/.*$
13 changes: 7 additions & 6 deletions aiida_optimade/cli/cmd_calc.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# pylint: disable=protected-access,too-many-locals,too-many-branches
import traceback
from typing import Tuple

import click
from aiida import load_profile
from aiida.cmdline.utils import echo
from tqdm import tqdm

from aiida_optimade.cli.cmd_aiida_optimade import cli
Expand Down Expand Up @@ -35,11 +38,10 @@
help="Suppress informational output.",
)
@click.pass_obj
def calc(obj: dict, fields: Tuple[str], force_yes: bool, silent: bool):
def calc(
obj: dict, fields: Tuple[str], force_yes: bool, silent: bool
): # pylint: disable=too-many-statements
"""Calculate OPTIMADE fields in the AiiDA database."""
from aiida import load_profile
from aiida.cmdline.utils import echo

# The default aiida.cmdline loglevel inherit from aiida loglevel is REPORT
# Here we use INFO loglevel for the operations
echo.CMDLINE_LOGGER.setLevel("INFO")
Expand All @@ -52,6 +54,7 @@ def calc(obj: dict, fields: Tuple[str], force_yes: bool, silent: bool):

try:
with disable_logging():
# pylint: disable=import-outside-toplevel
from aiida_optimade.routers.structures import STRUCTURES

extras_key = STRUCTURES.resource_mapper.PROJECT_PREFIX.split(".")[1]
Expand Down Expand Up @@ -139,8 +142,6 @@ def calc(obj: dict, fields: Tuple[str], force_yes: bool, silent: bool):
echo.echo_warning("Aborted!")
return
except Exception as exc: # pylint: disable=broad-except
import traceback

exception = traceback.format_exc()

LOGGER.error("Full exception from 'aiida-optimade calc' CLI:\n%s", exception)
Expand Down
18 changes: 9 additions & 9 deletions aiida_optimade/cli/cmd_init.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# pylint: disable=protected-access,too-many-statements
import traceback
from pathlib import Path
from typing import IO, Generator, Iterator, List, Union

import bson.json_util
import click
from aiida import load_profile
from aiida.cmdline.utils import echo
from tqdm import tqdm

from aiida_optimade.cli.cmd_aiida_optimade import cli
Expand Down Expand Up @@ -43,11 +47,10 @@
help="Filename to load as database (currently only usable for MongoDB).",
)
@click.pass_obj
def init(obj: dict, force: bool, silent: bool, mongo: bool, filename: str):
def init(
obj: dict, force: bool, silent: bool, mongo: bool, filename: str
): # pylint: disable=too-many-locals,too-many-branches
"""Initialize an AiiDA database to be served with AiiDA-OPTIMADE."""
from aiida import load_profile
from aiida.cmdline.utils import echo

# The default aiida.cmdline loglevel inherit from aiida loglevel is REPORT
# Here we use INFO loglevel for the operations
echo.CMDLINE_LOGGER.setLevel("INFO")
Expand All @@ -65,6 +68,7 @@ def init(obj: dict, force: bool, silent: bool, mongo: bool, filename: str):

try:
with disable_logging():
# pylint: disable=import-outside-toplevel
from aiida_optimade.routers.structures import STRUCTURES

if mongo:
Expand Down Expand Up @@ -136,8 +140,6 @@ def init(obj: dict, force: bool, silent: bool, mongo: bool, filename: str):
"Passing a filename currently only works for a MongoDB backend"
)

import bson.json_util

updated_pks = range(len(STRUCTURES_MONGO))
chunk_size = 2**24 # 16 MB

Expand All @@ -148,7 +150,7 @@ def init(obj: dict, force: bool, silent: bool, mongo: bool, filename: str):
"consider using --force to first drop the collection, if possible."
)

with open(filename, "r") as handle:
with open(filename, "r", encoding="utf8") as handle:
if silent:
all_chunks = read_chunks(handle, chunk_size=chunk_size)
else:
Expand Down Expand Up @@ -196,8 +198,6 @@ def init(obj: dict, force: bool, silent: bool, mongo: bool, filename: str):
entries=entries if mongo else None,
)
except Exception as exc: # pylint: disable=broad-except
import traceback

exception = traceback.format_exc()

LOGGER.error("Full exception from 'aiida-optimade init' CLI:\n%s", exception)
Expand Down
10 changes: 4 additions & 6 deletions aiida_optimade/cli/cmd_run.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# pylint: disable=too-many-arguments
import os

import click
import uvicorn
from aiida import load_profile

from aiida_optimade.cli.cmd_aiida_optimade import cli
from aiida_optimade.cli.options import LOGGING_LEVELS
Expand Down Expand Up @@ -45,10 +49,6 @@
@click.pass_obj
def run(obj: dict, log_level: str, debug: bool, host: str, port: int, reload: bool):
"""Run AiiDA-OPTIMADE server."""
import os

import uvicorn

if obj.get("dev", False):
debug = True

Expand All @@ -67,8 +67,6 @@ def run(obj: dict, log_level: str, debug: bool, host: str, port: int, reload: bo
os.environ["AIIDA_OPTIMADE_LOG_LEVEL"] = log_level.upper()

if os.getenv("AIIDA_PROFILE") is None:
from aiida import load_profile

try:
profile: str = obj.get("profile").name
except AttributeError:
Expand Down
9 changes: 8 additions & 1 deletion aiida_optimade/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,17 @@


class CustomServerConfig(ServerConfig):
"""Custom AiiDA-OPTIMADE server config.
This extends the server config class from the OPTIMADE Python server.
"""

query_group: Optional[str] = Field(
None,
description="The AiiDA Group containing the data that will be served, allowing one to serve a curated set of data from a given database.",
description=(
"The AiiDA Group containing the data that will be served, allowing one to "
"serve a curated set of data from a given database."
),
)


Expand Down
6 changes: 3 additions & 3 deletions aiida_optimade/entry_collections.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import warnings
from copy import deepcopy
from typing import Any, Dict, List, Optional, Set, Tuple, Union

from aiida.orm import Group
Expand Down Expand Up @@ -96,7 +97,7 @@ def set_data_returned(self, **criteria):
and criteria.get("filters", {}) != self._latest_filter
):
for key in ["limit", "offset"]:
if key in list(criteria.keys()):
if key in list(criteria):
del criteria[key]
self._latest_filter = criteria.get("filters", {}).copy()
LOGGER.debug("Setting data_returned using filter: %s", self._latest_filter)
Expand Down Expand Up @@ -130,7 +131,7 @@ def count(self, **kwargs) -> int:
"offset": kwargs.get("offset", None),
}
else:
for limiting_param in {"filters", "limit", "offset"}:
for limiting_param in ["filters", "limit", "offset"]:
if kwargs.get(limiting_param, None) != self._count.get(
limiting_param, None
):
Expand Down Expand Up @@ -438,7 +439,6 @@ def _find_extras_fields(self, filters: Union[dict, list]) -> None:
parameter.
"""
from copy import deepcopy

def __filter_fields_util( # pylint: disable=unused-private-member
_filters: Union[dict, list]
Expand Down
80 changes: 41 additions & 39 deletions aiida_optimade/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=ungrouped-imports
import json
import os
import warnings
Expand Down Expand Up @@ -117,46 +118,47 @@ async def startup():
LOGGER.info("AiiDA Profile: %s", profile_name)

# Load links
with open(Path(__file__).parent.joinpath("data/links.json").resolve()) as handle:
data = json.load(handle)

if CONFIG.debug:
data.append(
{
"id": "local",
"type": "links",
"name": "Local server",
"description": (
"Locally running instance of the AiiDA-OPTIMADE server using "
f"AiiDA profile {profile_name!r}."
),
"base_url": "http://localhost:5000",
"homepage": "https://github.com/aiidateam/aiida-optimade",
"link_type": "child",
}
)
data = json.loads(
Path(__file__).parent.joinpath("data/links.json").resolve().read_bytes()
)

processed = []
for link in data:
link["_id"] = {"$oid": mongo_id_for_database(link["id"], link["type"])}
processed.append(link)

LOGGER.info("Loading links")
if CONFIG.database_backend == SupportedBackend.MONGODB:
LOGGER.info(" Using real MongoDB.")
if links.LINKS.count(
filter={"id": {"$in": [_["id"] for _ in processed]}}
) != len(links.LINKS):
LOGGER.info(
" Will drop and reinsert links data in %s",
links.LINKS.collection.full_name,
)
links.LINKS.collection.drop()
links.LINKS.collection.insert_many(
bson.json_util.loads(bson.json_util.dumps(processed)),
)
else:
LOGGER.info(" Using mock MongoDB.")
if CONFIG.debug:
data.append(
{
"id": "local",
"type": "links",
"name": "Local server",
"description": (
"Locally running instance of the AiiDA-OPTIMADE server using "
f"AiiDA profile {profile_name!r}."
),
"base_url": "http://localhost:5000",
"homepage": "https://github.com/aiidateam/aiida-optimade",
"link_type": "child",
}
)

processed = []
for link in data:
link["_id"] = {"$oid": mongo_id_for_database(link["id"], link["type"])}
processed.append(link)

LOGGER.info("Loading links")
if CONFIG.database_backend == SupportedBackend.MONGODB:
LOGGER.info(" Using real MongoDB.")
if links.LINKS.count(
filter={"id": {"$in": [_["id"] for _ in processed]}}
) != len(links.LINKS):
LOGGER.info(
" Will drop and reinsert links data in %s",
links.LINKS.collection.full_name,
)
links.LINKS.collection.drop()
links.LINKS.collection.insert_many(
bson.json_util.loads(bson.json_util.dumps(processed)),
)
else:
LOGGER.info(" Using mock MongoDB.")
links.LINKS.collection.insert_many(
bson.json_util.loads(bson.json_util.dumps(processed)),
)
4 changes: 3 additions & 1 deletion aiida_optimade/mappers/entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ def all_aliases(cls) -> Tuple[Tuple[str, str]]:
)

@classmethod
def map_back(cls, entity_properties: Dict[str, Any]) -> dict:
def map_back( # pylint: disable=arguments-renamed
cls, entity_properties: Dict[str, Any]
) -> dict:
"""Map properties from AiiDA to OPTIMADE
Parameters:
Expand Down
1 change: 1 addition & 0 deletions aiida_optimade/middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=too-few-public-methods
import urllib.parse

from optimade.server.routers.utils import BASE_URL_PREFIXES
Expand Down
4 changes: 2 additions & 2 deletions aiida_optimade/models/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
)
from pydantic import Field

from aiida_optimade.config import CONFIG


def prefix_provider(string: str) -> str:
"""Prefix string with `_{provider}_`"""
from optimade.server.config import CONFIG

if string in CONFIG.provider_fields.get("structures", []):
return f"_{CONFIG.provider.prefix}_{string}"
return string
Expand Down
Loading

0 comments on commit 038c5fe

Please sign in to comment.