-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
633 additions
and
72 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,64 +1,88 @@ | ||
import logging | ||
import os | ||
import traceback | ||
from contextlib import asynccontextmanager | ||
from datetime import datetime | ||
|
||
import psycopg | ||
import asyncpg | ||
from dotenv import load_dotenv | ||
from flask import Flask, request | ||
from psycopg.rows import dict_row | ||
from fastapi import Depends, FastAPI, HTTPException, Query | ||
from fastapi.middleware.gzip import GZipMiddleware | ||
from fastapi_cache import FastAPICache | ||
from fastapi_cache.backends.inmemory import InMemoryBackend | ||
from fastapi_cache.decorator import cache | ||
|
||
load_dotenv() | ||
|
||
DATABASE_URL = os.getenv('DATABASE_URL') | ||
|
||
app = Flask(__name__) | ||
app.config['DATABASE_URL'] = os.getenv('DATABASE_URL') | ||
@asynccontextmanager | ||
async def lifespan(app: FastAPI): | ||
app.state.pool = await asyncpg.create_pool( | ||
DATABASE_URL, | ||
min_size=5, | ||
max_size=20 | ||
) | ||
FastAPICache.init(InMemoryBackend()) | ||
yield | ||
await app.state.pool.close() | ||
|
||
app = FastAPI(lifespan=lifespan) | ||
app.add_middleware(GZipMiddleware, minimum_size=1000) | ||
|
||
def get_db(): | ||
return psycopg.connect(app.config['DATABASE_URL']) | ||
async def get_db(): | ||
async with app.state.pool.acquire() as conn: | ||
yield conn | ||
|
||
|
||
@app.route('/') | ||
def index(): | ||
return 'It Works' | ||
@app.get("/") | ||
async def index(): | ||
return {"status": "It Works"} | ||
|
||
|
||
@app.get('/visits') | ||
def get_visits(): | ||
query = request.args | ||
@app.get("/visits") | ||
@cache(expire=300) | ||
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) | ||
): | ||
begin = datetime.fromisoformat(begin) | ||
end = datetime.fromisoformat(end) | ||
try: | ||
begin_date = datetime.fromisoformat(query['begin']) | ||
end_date = datetime.fromisoformat(query['end']) | ||
except ValueError as e: | ||
logging.error(traceback.format_exc(2, chain=False)) | ||
return 'Invalid date. Please check your input', 400 | ||
query = ''' | ||
SELECT * | ||
FROM visits | ||
WHERE visits.datetime BETWEEN (%s) AND (%s);''' | ||
with get_db() as conn: | ||
with conn.cursor(row_factory=dict_row) as c: | ||
c.execute(query, [begin_date, end_date]) | ||
res = c.fetchall() | ||
return res | ||
query = """ | ||
SELECT * | ||
FROM visits | ||
WHERE visits.datetime BETWEEN $1 AND $2 | ||
""" | ||
records = await db.fetch(query, begin, end) | ||
return records | ||
except Exception as e: | ||
logging.error(f"Error fetching visits: {str(e)}") | ||
raise HTTPException( | ||
status_code=500, | ||
detail="Internal server error occurred while fetching visits" | ||
) | ||
|
||
|
||
@app.get('/registrations') | ||
def get_registrations(): | ||
query = request.args | ||
@app.get("/registrations") | ||
@cache(expire=300) | ||
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) | ||
): | ||
begin = datetime.fromisoformat(begin) | ||
end = datetime.fromisoformat(end) | ||
try: | ||
begin_date = datetime.fromisoformat(query['begin']) | ||
end_date = datetime.fromisoformat(query['end']) | ||
except ValueError as e: | ||
logging.error(traceback.format_exc(2, chain=False)) | ||
return 'Invalid date. Please check your input', 400 | ||
query = ''' | ||
SELECT * | ||
FROM registrations | ||
WHERE registrations.datetime BETWEEN (%s) AND (%s);''' | ||
with get_db() as conn: | ||
with conn.cursor(row_factory=dict_row) as c: | ||
c.execute(query, [begin_date, end_date]) | ||
res = c.fetchall() | ||
return res | ||
query = """ | ||
SELECT * | ||
FROM registrations | ||
WHERE registrations.datetime BETWEEN $1 AND $2 | ||
""" | ||
records = await db.fetch(query, begin, end) | ||
return records | ||
except Exception as e: | ||
logging.error(f"Error fetching registrations: {str(e)}") | ||
raise HTTPException( | ||
status_code=500, | ||
detail="Internal server error occurred while fetching registrations" | ||
) |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.