Spaces:
Paused
Paused
Create routes.py
Browse files
routes.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Depends
|
| 2 |
+
from sqlalchemy.orm import Session
|
| 3 |
+
from app.database import SessionLocal
|
| 4 |
+
from app.models import APIKey, User
|
| 5 |
+
import secrets
|
| 6 |
+
|
| 7 |
+
router = APIRouter()
|
| 8 |
+
|
| 9 |
+
def get_db():
|
| 10 |
+
db = SessionLocal()
|
| 11 |
+
try:
|
| 12 |
+
yield db
|
| 13 |
+
finally:
|
| 14 |
+
db.close()
|
| 15 |
+
|
| 16 |
+
@router.post("/generate-key")
|
| 17 |
+
def generate_key(user_id: int, db: Session = Depends(get_db)):
|
| 18 |
+
api_key = secrets.token_hex(32)
|
| 19 |
+
new_key = APIKey(user_id=user_id, key=api_key)
|
| 20 |
+
db.add(new_key)
|
| 21 |
+
db.commit()
|
| 22 |
+
return {"api_key": api_key}
|