Skip to content

Commit

Permalink
⚡️ Caching strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
lleans committed Aug 6, 2024
1 parent 6b7033c commit bbd74c3
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from os import environ
from typing import Annotated
from contextlib import asynccontextmanager
from hashlib import md5

from aiohttp import ClientSession

Expand Down Expand Up @@ -29,6 +30,8 @@ async def lifespan(_):
FastAPICache.init(RedisBackend(redis), prefix="muslimproapi-cache")
yield

cache_expire: int = 10800

description: str = """
# Muslim Pro Scrapper 🕌
Simple scrapper using aiohttp and pyquery to get Praytime for moslem people
Expand Down Expand Up @@ -98,7 +101,26 @@ async def where_ip(session: ClientSession, ip_address: str) -> str:
}
async with session.get(url+ip_address, params=params, headers=headers) as response:
res: dict = await response.json()
return f"{res['city']}, {res['regionName']}, {res['country']}, {res['continent']}"
return f"{res['city']}, {res['regionName']}, {res['country']}"

def request_key_builder(
_,
namespace: str = "",
*,
request: Request = None,
**kwargs,
):
from re import split
parts = split(r'[,\s]+', request.url.path.removeprefix('/'))
city = parts[0] if len(parts) > 0 else request.url.path

md5_hash = md5()
md5_hash.update(city.lower().encode('utf-8'))

return ":".join([
namespace,
md5_hash.hexdigest()
])


class ModelResponse(BaseModel):
Expand Down Expand Up @@ -231,14 +253,14 @@ async def get_location_based(request: Request) -> RedirectResponse:
'content': {
'application/json': {
'example': {
"status_code": 422,
"status_code": 400,
"message": "Bad request, please check your datatypes or make sure to fill all parameter",
"data": "null"
}
}
}}
})
@cache(expire=10800)
@cache(expire=cache_expire, key_builder=request_key_builder, namespace="test")
async def main_app(
query: Annotated[str, Path(
title="Location query", description="Pass your city/country name")],
Expand Down

0 comments on commit bbd74c3

Please sign in to comment.