Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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(
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# ---
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
@app.
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|