Skip to content

Commit

Permalink
stash more
Browse files Browse the repository at this point in the history
  • Loading branch information
jsstevenson committed Jan 14, 2025
1 parent 292f457 commit bb680ed
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repos:
- id: mixed-line-ending
args: [ --fix=lf ]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.5.0
rev: v0.8.6
hooks:
- id: ruff
- id: ruff-format
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ select = [
"ARG", # https://docs.astral.sh/ruff/rules/#flake8-unused-arguments-arg
"PTH", # https://docs.astral.sh/ruff/rules/#flake8-use-pathlib-pth
"PGH", # https://docs.astral.sh/ruff/rules/#pygrep-hooks-pgh
"FAST", # https://docs.astral.sh/ruff/rules/#fastapi-fast
"PERF", # https://docs.astral.sh/ruff/rules/#perflint-perf
"FURB", # https://docs.astral.sh/ruff/rules/#refurb-furb
"RUF", # https://docs.astral.sh/ruff/rules/#ruff-specific-rules-ruf
Expand All @@ -139,6 +140,7 @@ fixable = [
"PT",
"RSE",
"SIM",
"FAST",
"PERF",
"FURB",
"RUF"
Expand Down
3 changes: 2 additions & 1 deletion src/gene/database/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import click

from gene.config import config
from gene.schemas import AwsEnvName, RecordType, RefType, SourceMeta, SourceName


Expand Down Expand Up @@ -62,7 +63,7 @@ def _check_delete_okay() -> bool:
:raise DatabaseWriteException: if skip confirmation variable is set -- manual
approval is required.
"""
if environ.get(AWS_ENV_VAR_NAME, "") == AwsEnvName.PRODUCTION:
if config.env == AwsEnvName.PRODUCTION:
if environ.get(SKIP_AWS_DB_ENV_NAME, "") == "true":
err_msg = f"Must unset {SKIP_AWS_DB_ENV_NAME} env variable to enable drop_db()"
raise DatabaseWriteException(err_msg)
Expand Down
4 changes: 2 additions & 2 deletions src/gene/etl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
from .ncbi import NCBI

__all__ = [
"Ensembl",
"HGNC",
"NCBI",
"GeneNormalizerEtlError",
"Ensembl",
"GeneFileVersionError",
"GeneNormalizerEtlError",
"GeneSourceFetchError",
]
54 changes: 39 additions & 15 deletions src/gene/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

import html
import os
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from enum import Enum
from typing import Annotated

from fastapi import FastAPI, HTTPException, Query
from fastapi import FastAPI, HTTPException, Query, Request

from gene import __version__
from gene.database.database import (
Expand All @@ -13,6 +16,7 @@
AwsEnvName,
create_db,
)
from gene.logging import initialize_logs
from gene.query import InvalidParameterException, QueryHandler
from gene.schemas import (
NormalizeService,
Expand All @@ -31,8 +35,19 @@ class _Tag(str, Enum):
META = "Meta"


db = create_db()
query_handler = QueryHandler(db)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator:
"""Perform operations that interact with the lifespan of the FastAPI instance.
See https://fastapi.tiangolo.com/advanced/events/#lifespan.
:param app: FastAPI instance
"""
initialize_logs()

db = create_db()
app.state.query_handler = QueryHandler(db)
yield


description = """
The Gene Normalizer provides tools for resolving ambiguous gene references to
Expand Down Expand Up @@ -82,17 +97,19 @@ class _Tag(str, Enum):
"/gene/search",
summary=read_query_summary,
response_description=response_description,
response_model=SearchService,
description=search_description,
tags=[_Tag.QUERY],
)
def search(
q: str = Query(..., description=q_descr),
incl: str | None = Query(None, description=incl_descr),
excl: str | None = Query(None, description=excl_descr),
request: Request,
q: Annotated[str, Query(..., description=q_descr)],
incl: Annotated[str | None, Query(None, description=incl_descr)],
excl: Annotated[str | None, Query(None, description=excl_descr)],
) -> SearchService:
"""Return strongest match concepts to query string provided by user.
:param request: the HTTP request context, supplied by FastAPI, used to get
query response class
:param str q: gene search term
:param Optional[str] incl: comma-separated list of sources to include,
with all others excluded. Raises HTTPException if both `incl` and
Expand All @@ -103,7 +120,9 @@ def search(
:return: JSON response with matched records and source metadata
"""
try:
resp = query_handler.search(html.unescape(q), incl=incl, excl=excl)
resp = request.app.state.query_handler.search(
html.unescape(q), incl=incl, excl=excl
)
except InvalidParameterException as e:
raise HTTPException(status_code=422, detail=str(e)) from e
return resp
Expand All @@ -119,18 +138,22 @@ def search(
"/gene/normalize",
summary=normalize_summary,
response_description=normalize_response_descr,
response_model=NormalizeService,
response_model_exclude_none=True,
description=normalize_descr,
tags=[_Tag.QUERY],
)
def normalize(q: str = Query(..., description=normalize_q_descr)) -> NormalizeService:
def normalize(
request: Request,
q: Annotated[str, Query(..., description=normalize_q_descr)],
) -> NormalizeService:
"""Return strongest match concepts to query string provided by user.
:param request: the HTTP request context, supplied by FastAPI, used to get
query response class
:param str q: gene search term
:return: JSON response with normalized gene concept
"""
return query_handler.normalize(html.unescape(q))
return request.app.state.query_handler.normalize(html.unescape(q))


unmerged_matches_summary = (
Expand All @@ -151,25 +174,26 @@ def normalize(q: str = Query(..., description=normalize_q_descr)) -> NormalizeSe
summary=unmerged_matches_summary,
operation_id="getUnmergedRecords",
response_description=unmerged_response_descr,
response_model=UnmergedNormalizationService,
description=unmerged_normalize_description,
tags=[_Tag.QUERY],
)
def normalize_unmerged(
q: str = Query(..., description=normalize_q_descr),
request: Request,
q: Annotated[str, Query(..., description=normalize_q_descr)],
) -> UnmergedNormalizationService:
"""Return all individual records associated with a normalized concept.
:param request: the HTTP request context, supplied by FastAPI, used to get
query response class
:param q: Gene search term
:returns: JSON response with matching normalized record and source metadata
"""
return query_handler.normalize_unmerged(html.unescape(q))
return request.app.state.query_handler.normalize_unmerged(html.unescape(q))


@app.get(
"/service_info",
summary="Get basic service information",
response_model=ServiceInfo,
description="Retrieve service metadata, such as versioning and contact info. Structured in conformance with the [GA4GH service info API specification](https://www.ga4gh.org/product/service-info/)",
tags=[_Tag.META],
)
Expand Down
5 changes: 4 additions & 1 deletion src/gene/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,9 @@ class ServiceType(BaseModel):
version: Literal[__version__] = __version__


LOCAL_DEV_ENV_NAME = "local_dev"


class AwsEnvName(str, Enum):
"""AWS environment name that is being used"""

Expand Down Expand Up @@ -776,5 +779,5 @@ class ServiceInfo(BaseModel):
"2024-03-04T00:00:00.000000+00:00"
)
updatedAt: str | None = None # noqa: N815
environment: AwsEnvName | None = None
environment: AwsEnvName | Literal[LOCAL_DEV_ENV_NAME] | None = None
version: Literal[__version__] = __version__

0 comments on commit bb680ed

Please sign in to comment.