Skip to content

Commit

Permalink
Add aioredis for storing already decoded ticket contracts
Browse files Browse the repository at this point in the history
Signed-off-by: David Sn <[email protected]>
  • Loading branch information
divadsn committed Sep 9, 2021
1 parent c6a5ead commit ddfb87a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
17 changes: 17 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import base64
import os
import time

from datetime import datetime, timedelta
from io import BytesIO

import aiohttp
import aioredis
import zxingcpp

from fastapi import FastAPI, Header, Request
Expand All @@ -16,6 +18,9 @@
# Ticket contract endpoint
CONTRACT_URL = "https://api.kkm.krakow.pl/api/v1/mkkm/tickets/{ticket_guid}/contract"

# Redis settings
REDIS_URL = os.getenv("REDIS_URL", "redis://user:sEcRet@localhost/")


class HTTPException(Exception):
def __init__(self, status_code: int, message: str):
Expand All @@ -42,6 +47,13 @@ class ErrorResponse(BaseModel):
redoc_url=None
)

redis = aioredis.from_url(REDIS_URL, decode_responses=True)


@app.on_event("shutdown")
async def shutdown_event():
await redis.close()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
Expand All @@ -68,6 +80,9 @@ async def http_exception_handler(request: Request, exception: HTTPException):
})
async def get_contract(ticket_guid: str, authorization: str = Header(Required)):
"""Returns decoded AZTEC barcode data"""
if await redis.exists(f"ticket:{ticket_guid}:contract"):
return {"aztec": await redis.get(f"ticket:{ticket_guid}:contract")}

auth_headers = {
"User-Agent": "mobileKKM/contract_proxy",
"Authorization": authorization
Expand All @@ -87,4 +102,6 @@ async def get_contract(ticket_guid: str, authorization: str = Header(Required)):
raise HTTPException(status_code=500, message="Could not decode barcode from image.") from exc

expires = datetime.utcnow().replace(second=0, microsecond=0) + timedelta(minutes=2)

await redis.set(f"ticket:{ticket_guid}:contract", result.text, ex=(expires - datetime.utcnow()).seconds)
return {"aztec": result.text, "expires": expires}
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
aiohttp
aioredis
fastapi
pillow
pydantic
uvicorn
zxing-cpp

0 comments on commit ddfb87a

Please sign in to comment.