Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions app/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)


@asynccontextmanager
async def lifespan(app: FastAPI):
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL is not set. Define it in the environment or .env file.")
raise RuntimeError(
"DATABASE_URL is not set. "
"Define it in the environment or .env file."
)
try:
app.state.pool = await asyncpg.create_pool(
DATABASE_URL,
Expand All @@ -36,14 +40,19 @@ async def lifespan(app: FastAPI):
logging.info("Connected to database successfully")
except Exception as e:
logging.error(f"Failed to connect to the database: {str(e)}")
raise RuntimeError("Failed to connect to the database. Check DATABASE_URL and DB availability.") from e
raise RuntimeError(
"Failed to connect to the database. "
"Check DATABASE_URL and DB availability."
) from e
FastAPICache.init(InMemoryBackend())
yield
await app.state.pool.close()


app = FastAPI(lifespan=lifespan)
app.add_middleware(GZipMiddleware, minimum_size=1000)


async def get_db():
async with app.state.pool.acquire() as conn:
yield conn
Expand All @@ -53,8 +62,9 @@ async def get_db():
async def index():
return {"status": "It Works"}


@app.get("/health")
async def health(db = Depends(get_db)):
async def health(db=Depends(get_db)):
try:
await db.execute("SELECT 1")
return {"status": "ok", "db": "ok"}
Expand Down Expand Up @@ -100,7 +110,7 @@ async def generator():
async def get_visits(
begin: str = Query(..., description="Start date in ISO format"),
end: str = Query(..., description="End date in ISO format"),
db = Depends(get_db)
db=Depends(get_db)
):
begin = datetime.fromisoformat(begin)
end = datetime.fromisoformat(end)
Expand All @@ -118,11 +128,12 @@ async def get_visits(
detail="Internal server error occurred while fetching visits"
)


@app.get("/registrations")
async def get_registrations(
begin: str = Query(..., description="Start date in ISO format"),
end: str = Query(..., description="End date in ISO format"),
db = Depends(get_db)
db=Depends(get_db)
):
begin = datetime.fromisoformat(begin)
end = datetime.fromisoformat(end)
Expand Down
9 changes: 9 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
line-length = 80

[lint.per-file-ignores]
# init modules can contain the local imports, logic, unused imports
"__init__.py" = ["F401"]

[lint]
preview = true
select = ["E", "F", "C90"]
7 changes: 6 additions & 1 deletion tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

PORT = os.getenv('PORT')


def test_server():
response = requests.get('http://localhost:4000/')
assert response.status_code == 200
Expand All @@ -14,6 +15,10 @@ def test_server():
assert response.json()[0] == {
"datetime": "2023-03-01T10:36:22",
"platform": "web",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.6",
"user_agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.6"
),
"visit_id": "1de9ea66-70d3-4a1f-8735-df5ef7697fb9"
}