Skip to content

Commit

Permalink
Move decs initialization to lifespan
Browse files Browse the repository at this point in the history
  • Loading branch information
viniciusandrade committed Oct 8, 2024
1 parent 65b5e40 commit 20019a7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 4 additions & 5 deletions controller/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,13 @@
ENCODE_REGEX = re.compile(r"\^[ds]\d+")
SOLR_TIMEOUT = int(os.getenv("SOLR_TIMEOUT", 10))

# Initialize DeCS decoder
decs = DecodDeCS()

@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.client = httpx.AsyncClient()
app.state.decs = DecodDeCS() # Initialize DeCS decoder
yield
await app.state.client.aclose()
await app.state.decs.close()


app = FastAPI(lifespan=lifespan)
Expand Down Expand Up @@ -193,7 +192,7 @@ async def search(
# Run regular expression and decode if found thesaurus codes
if ENCODE_REGEX.search(result):
logger.info(f"Applying decod for language {lang}")
result = decs.decode(result, lang)
result = app.state.decs.decode(result, lang)

# Remove subfields marks of non decoded descriptors
result = re.sub(r"(\^d)", "", result)
Expand Down Expand Up @@ -228,6 +227,6 @@ async def healthcheck(
}

result = await send_post_command(query_map, search_url)
result = decs.decode(result, lang)
result = app.state.decs.decode(result, lang)

return JSONResponse(content=json.loads(result), headers={"Cache-Control": "no-cache"})
4 changes: 4 additions & 0 deletions controller/decode_decs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ def __init__(self, redis_host='iahx_controller_cache', redis_port=6379, redis_db
self.redis_client = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
self.REGEX = re.compile(r"(\^[ds])(\d+)") # Pre-compile regex pattern

def close(self):
if self.redis_client:
self.redis_client.close()

def decode(self, text, lang):
"""
Decode a given string by replacing ^d or ^s codes with their corresponding descriptors from Redis.
Expand Down

0 comments on commit 20019a7

Please sign in to comment.