|
1 | 1 | import logging |
2 | 2 | import os |
3 | | -import traceback |
| 3 | +from contextlib import asynccontextmanager |
4 | 4 | from datetime import datetime |
5 | 5 |
|
6 | | -import psycopg |
| 6 | +import asyncpg |
7 | 7 | from dotenv import load_dotenv |
8 | | -from flask import Flask, request |
9 | | -from psycopg.rows import dict_row |
| 8 | +from fastapi import Depends, FastAPI, HTTPException, Query |
| 9 | +from fastapi.middleware.gzip import GZipMiddleware |
| 10 | +from fastapi_cache import FastAPICache |
| 11 | +from fastapi_cache.backends.inmemory import InMemoryBackend |
| 12 | +from fastapi_cache.decorator import cache |
10 | 13 |
|
11 | 14 | load_dotenv() |
12 | 15 |
|
| 16 | +DATABASE_URL = os.getenv('DATABASE_URL') |
13 | 17 |
|
14 | | -app = Flask(__name__) |
15 | | -app.config['DATABASE_URL'] = os.getenv('DATABASE_URL') |
| 18 | +@asynccontextmanager |
| 19 | +async def lifespan(app: FastAPI): |
| 20 | + app.state.pool = await asyncpg.create_pool( |
| 21 | + DATABASE_URL, |
| 22 | + min_size=5, |
| 23 | + max_size=20 |
| 24 | + ) |
| 25 | + FastAPICache.init(InMemoryBackend()) |
| 26 | + yield |
| 27 | + await app.state.pool.close() |
16 | 28 |
|
| 29 | +app = FastAPI(lifespan=lifespan) |
| 30 | +app.add_middleware(GZipMiddleware, minimum_size=1000) |
17 | 31 |
|
18 | | -def get_db(): |
19 | | - return psycopg.connect(app.config['DATABASE_URL']) |
| 32 | +async def get_db(): |
| 33 | + async with app.state.pool.acquire() as conn: |
| 34 | + yield conn |
20 | 35 |
|
21 | 36 |
|
22 | | -@app.route('/') |
23 | | -def index(): |
24 | | - return 'It Works' |
| 37 | +@app.get("/") |
| 38 | +async def index(): |
| 39 | + return {"status": "It Works"} |
25 | 40 |
|
26 | 41 |
|
27 | | -@app.get('/visits') |
28 | | -def get_visits(): |
29 | | - query = request.args |
| 42 | +@app.get("/visits") |
| 43 | +@cache(expire=300) |
| 44 | +async def get_visits( |
| 45 | + begin: str = Query(..., description="Start date in ISO format"), |
| 46 | + end: str = Query(..., description="End date in ISO format"), |
| 47 | + db = Depends(get_db) |
| 48 | +): |
| 49 | + begin = datetime.fromisoformat(begin) |
| 50 | + end = datetime.fromisoformat(end) |
30 | 51 | try: |
31 | | - begin_date = datetime.fromisoformat(query['begin']) |
32 | | - end_date = datetime.fromisoformat(query['end']) |
33 | | - except ValueError as e: |
34 | | - logging.error(traceback.format_exc(2, chain=False)) |
35 | | - return 'Invalid date. Please check your input', 400 |
36 | | - query = ''' |
37 | | - SELECT * |
38 | | - FROM visits |
39 | | - WHERE visits.datetime BETWEEN (%s) AND (%s);''' |
40 | | - with get_db() as conn: |
41 | | - with conn.cursor(row_factory=dict_row) as c: |
42 | | - c.execute(query, [begin_date, end_date]) |
43 | | - res = c.fetchall() |
44 | | - return res |
| 52 | + query = """ |
| 53 | + SELECT * |
| 54 | + FROM visits |
| 55 | + WHERE visits.datetime BETWEEN $1 AND $2 |
| 56 | + """ |
| 57 | + records = await db.fetch(query, begin, end) |
| 58 | + return records |
| 59 | + except Exception as e: |
| 60 | + logging.error(f"Error fetching visits: {str(e)}") |
| 61 | + raise HTTPException( |
| 62 | + status_code=500, |
| 63 | + detail="Internal server error occurred while fetching visits" |
| 64 | + ) |
45 | 65 |
|
46 | | - |
47 | | -@app.get('/registrations') |
48 | | -def get_registrations(): |
49 | | - query = request.args |
| 66 | +@app.get("/registrations") |
| 67 | +@cache(expire=300) |
| 68 | +async def get_registrations( |
| 69 | + begin: str = Query(..., description="Start date in ISO format"), |
| 70 | + end: str = Query(..., description="End date in ISO format"), |
| 71 | + db = Depends(get_db) |
| 72 | +): |
| 73 | + begin = datetime.fromisoformat(begin) |
| 74 | + end = datetime.fromisoformat(end) |
50 | 75 | try: |
51 | | - begin_date = datetime.fromisoformat(query['begin']) |
52 | | - end_date = datetime.fromisoformat(query['end']) |
53 | | - except ValueError as e: |
54 | | - logging.error(traceback.format_exc(2, chain=False)) |
55 | | - return 'Invalid date. Please check your input', 400 |
56 | | - query = ''' |
57 | | - SELECT * |
58 | | - FROM registrations |
59 | | - WHERE registrations.datetime BETWEEN (%s) AND (%s);''' |
60 | | - with get_db() as conn: |
61 | | - with conn.cursor(row_factory=dict_row) as c: |
62 | | - c.execute(query, [begin_date, end_date]) |
63 | | - res = c.fetchall() |
64 | | - return res |
| 76 | + query = """ |
| 77 | + SELECT * |
| 78 | + FROM registrations |
| 79 | + WHERE registrations.datetime BETWEEN $1 AND $2 |
| 80 | + """ |
| 81 | + records = await db.fetch(query, begin, end) |
| 82 | + return records |
| 83 | + except Exception as e: |
| 84 | + logging.error(f"Error fetching registrations: {str(e)}") |
| 85 | + raise HTTPException( |
| 86 | + status_code=500, |
| 87 | + detail="Internal server error occurred while fetching registrations" |
| 88 | + ) |
0 commit comments