Spaces:
Sleeping
Sleeping
Download app.py from Ukandu/email-handler: direct link, hf CLI and curl.
- Browser
- Download file 3.58 kB
-
https://huggingface.co/spaces/Ukandu/email-handler/resolve/main/app.py
- Command line
-
hf download hf://spaces/Ukandu/email-handler/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Ukandu/email-handler/resolve/main/app.py
3.58 kB
| import os | |
| from fastapi import FastAPI, Request, HTTPException, Depends | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, EmailStr | |
| from sqlalchemy import create_engine, Column, Integer, String, DateTime | |
| from sqlalchemy.orm import sessionmaker, declarative_base | |
| from datetime import datetime | |
| from slowapi import Limiter | |
| from slowapi.util import get_remote_address | |
| from slowapi.errors import RateLimitExceeded | |
| from slowapi.middleware import SlowAPIMiddleware | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv() | |
| API_KEY = os.getenv("API_KEY", "supersecretkey") | |
| # --- FastAPI Setup --- | |
| app = FastAPI( | |
| title="Subscription API", | |
| version="1.0", | |
| docs_url="/docs", | |
| redoc_url="/redoc", | |
| ) | |
| # --- CORS --- | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # change to your frontend domain in production | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --- Rate Limiting --- | |
| limiter = Limiter(key_func=get_remote_address) | |
| app.state.limiter = limiter | |
| app.add_exception_handler(RateLimitExceeded, lambda r, e: HTTPException(429, "Too many requests")) | |
| app.add_middleware(SlowAPIMiddleware) | |
| # --- Database Setup --- | |
| DATABASE_URL = "sqlite:///./subscribers.db" | |
| engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) | |
| SessionLocal = sessionmaker(bind=engine) | |
| Base = declarative_base() | |
| class Subscriber(Base): | |
| __tablename__ = "subscribers" | |
| id = Column(Integer, primary_key=True, index=True) | |
| email = Column(String, unique=True, index=True, nullable=False) | |
| created_at = Column(DateTime, default=datetime.utcnow) | |
| Base.metadata.create_all(bind=engine) | |
| # --- Request Schema --- | |
| class SubscriptionRequest(BaseModel): | |
| email: EmailStr | |
| # --- Dependency --- | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |
| # --- API Key Protection --- | |
| def verify_api_key(request: Request): | |
| client_key = request.headers.get("x-api-key") | |
| if client_key != API_KEY: | |
| raise HTTPException(status_code=403, detail="Invalid API Key") | |
| # --- Routes --- | |
| def health_check(): | |
| return {"status": "API is running"} | |
| # @app.post("/subscribe") | |
| # @limiter.limit("5/minute") | |
| # def subscribe( | |
| # request: Request, | |
| # payload: SubscriptionRequest, | |
| # db=Depends(get_db), | |
| # _: None = Depends(verify_api_key), | |
| # ): | |
| # existing = db.query(Subscriber).filter(Subscriber.email == payload.email).first() | |
| # if existing: | |
| # raise HTTPException(status_code=400, detail="Email already subscribed") | |
| # new_subscriber = Subscriber(email=payload.email) | |
| # db.add(new_subscriber) | |
| # db.commit() | |
| # return {"message": "Successfully subscribed"} | |
| def subscribe( | |
| payload: SubscriptionRequest, | |
| db=Depends(get_db), | |
| _: None = Depends(verify_api_key), | |
| ): | |
| # Check if email already exists | |
| existing = db.query(Subscriber).filter(Subscriber.email == payload.email).first() | |
| if existing: | |
| # Email already subscribed | |
| return {"message": f"{payload.email} is already subscribed!"} | |
| # Add new subscriber | |
| new_subscriber = Subscriber(email=payload.email) | |
| db.add(new_subscriber) | |
| db.commit() | |
| return {"message": f"Successfully subscribed: {payload.email}"} | |
| def list_subscribers(db=Depends(get_db)): | |
| subscribers = db.query(Subscriber).all() | |
| # Return only emails to keep it simple | |
| return {"emails": [s.email for s in subscribers], "count": len(subscribers)} |