Ukandu commited on
Commit
fa87e11
·
verified ·
1 Parent(s): fdb266b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -101
app.py CHANGED
@@ -1,101 +1,112 @@
1
- import os
2
- from fastapi import FastAPI, Request, HTTPException, Depends
3
- from fastapi.middleware.cors import CORSMiddleware
4
- from pydantic import BaseModel, EmailStr
5
- from sqlalchemy import create_engine, Column, Integer, String, DateTime
6
- from sqlalchemy.orm import sessionmaker, declarative_base
7
- from datetime import datetime
8
- from slowapi import Limiter
9
- from slowapi.util import get_remote_address
10
- from slowapi.errors import RateLimitExceeded
11
- from slowapi.middleware import SlowAPIMiddleware
12
- from dotenv import load_dotenv
13
-
14
- # Load environment variables
15
- load_dotenv()
16
-
17
- API_KEY = os.getenv("API_KEY", "supersecretkey")
18
-
19
- # --- FastAPI Setup ---
20
- app = FastAPI(title="Subscription API", version="1.0")
21
-
22
- # --- CORS ---
23
- app.add_middleware(
24
- CORSMiddleware,
25
- allow_origins=["*"], # change to your frontend domain in production
26
- allow_credentials=True,
27
- allow_methods=["*"],
28
- allow_headers=["*"],
29
- )
30
-
31
- # --- Rate Limiting ---
32
- limiter = Limiter(key_func=get_remote_address)
33
- app.state.limiter = limiter
34
- app.add_exception_handler(RateLimitExceeded, lambda r, e: HTTPException(429, "Too many requests"))
35
- app.add_middleware(SlowAPIMiddleware)
36
-
37
- # --- Database Setup ---
38
- DATABASE_URL = "sqlite:///./subscribers.db"
39
-
40
- engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
41
- SessionLocal = sessionmaker(bind=engine)
42
- Base = declarative_base()
43
-
44
-
45
- class Subscriber(Base):
46
- __tablename__ = "subscribers"
47
-
48
- id = Column(Integer, primary_key=True, index=True)
49
- email = Column(String, unique=True, index=True, nullable=False)
50
- created_at = Column(DateTime, default=datetime.utcnow)
51
-
52
-
53
- Base.metadata.create_all(bind=engine)
54
-
55
-
56
- # --- Request Schema ---
57
- class SubscriptionRequest(BaseModel):
58
- email: EmailStr
59
-
60
-
61
- # --- Dependency ---
62
- def get_db():
63
- db = SessionLocal()
64
- try:
65
- yield db
66
- finally:
67
- db.close()
68
-
69
-
70
- # --- API Key Protection ---
71
- def verify_api_key(request: Request):
72
- client_key = request.headers.get("x-api-key")
73
- if client_key != API_KEY:
74
- raise HTTPException(status_code=403, detail="Invalid API Key")
75
-
76
-
77
- # --- Routes ---
78
-
79
- @app.get("/")
80
- def health_check():
81
- return {"status": "API is running"}
82
-
83
-
84
- @app.post("/subscribe")
85
- @limiter.limit("5/minute")
86
- def subscribe(
87
- request: Request,
88
- payload: SubscriptionRequest,
89
- db=Depends(get_db),
90
- _: None = Depends(verify_api_key),
91
- ):
92
- existing = db.query(Subscriber).filter(Subscriber.email == payload.email).first()
93
-
94
- if existing:
95
- raise HTTPException(status_code=400, detail="Email already subscribed")
96
-
97
- new_subscriber = Subscriber(email=payload.email)
98
- db.add(new_subscriber)
99
- db.commit()
100
-
101
- return {"message": "Successfully subscribed"}
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fastapi import FastAPI, Request, HTTPException, Depends
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel, EmailStr
5
+ from sqlalchemy import create_engine, Column, Integer, String, DateTime
6
+ from sqlalchemy.orm import sessionmaker, declarative_base
7
+ from datetime import datetime
8
+ from slowapi import Limiter
9
+ from slowapi.util import get_remote_address
10
+ from slowapi.errors import RateLimitExceeded
11
+ from slowapi.middleware import SlowAPIMiddleware
12
+ from dotenv import load_dotenv
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ API_KEY = os.getenv("API_KEY", "supersecretkey")
18
+
19
+ # --- FastAPI Setup ---
20
+ app = FastAPI(
21
+ title="Subscription API",
22
+ version="1.0",
23
+ docs_url="/docs",
24
+ redoc_url="/redoc",
25
+ )
26
+
27
+ # --- CORS ---
28
+ app.add_middleware(
29
+ CORSMiddleware,
30
+ allow_origins=["*"], # change to your frontend domain in production
31
+ allow_credentials=True,
32
+ allow_methods=["*"],
33
+ allow_headers=["*"],
34
+ )
35
+
36
+ # --- Rate Limiting ---
37
+ limiter = Limiter(key_func=get_remote_address)
38
+ app.state.limiter = limiter
39
+ app.add_exception_handler(RateLimitExceeded, lambda r, e: HTTPException(429, "Too many requests"))
40
+ app.add_middleware(SlowAPIMiddleware)
41
+
42
+ # --- Database Setup ---
43
+ DATABASE_URL = "sqlite:///./subscribers.db"
44
+
45
+ engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
46
+ SessionLocal = sessionmaker(bind=engine)
47
+ Base = declarative_base()
48
+
49
+
50
+ class Subscriber(Base):
51
+ __tablename__ = "subscribers"
52
+
53
+ id = Column(Integer, primary_key=True, index=True)
54
+ email = Column(String, unique=True, index=True, nullable=False)
55
+ created_at = Column(DateTime, default=datetime.utcnow)
56
+
57
+
58
+ Base.metadata.create_all(bind=engine)
59
+
60
+
61
+ # --- Request Schema ---
62
+ class SubscriptionRequest(BaseModel):
63
+ email: EmailStr
64
+
65
+
66
+ # --- Dependency ---
67
+ def get_db():
68
+ db = SessionLocal()
69
+ try:
70
+ yield db
71
+ finally:
72
+ db.close()
73
+
74
+
75
+ # --- API Key Protection ---
76
+ def verify_api_key(request: Request):
77
+ client_key = request.headers.get("x-api-key")
78
+ if client_key != API_KEY:
79
+ raise HTTPException(status_code=403, detail="Invalid API Key")
80
+
81
+
82
+ # --- Routes ---
83
+
84
+ @app.get("/")
85
+ def health_check():
86
+ return {"status": "API is running"}
87
+
88
+
89
+ @app.post("/subscribe")
90
+ @limiter.limit("5/minute")
91
+ def subscribe(
92
+ request: Request,
93
+ payload: SubscriptionRequest,
94
+ db=Depends(get_db),
95
+ _: None = Depends(verify_api_key),
96
+ ):
97
+ existing = db.query(Subscriber).filter(Subscriber.email == payload.email).first()
98
+
99
+ if existing:
100
+ raise HTTPException(status_code=400, detail="Email already subscribed")
101
+
102
+ new_subscriber = Subscriber(email=payload.email)
103
+ db.add(new_subscriber)
104
+ db.commit()
105
+
106
+ return {"message": "Successfully subscribed"}
107
+
108
+ @app.get("/subscribers")
109
+ def list_subscribers(db=Depends(get_db)):
110
+ subscribers = db.query(Subscriber).all()
111
+ return {"count": len(subscribers)}
112
+