Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI, Request | |
| import psycopg2 | |
| import os | |
| app = FastAPI() | |
| # π₯ Put your CockroachDB connection string in Hugging Face Secrets | |
| DB_URL = os.getenv("DB_URL") | |
| conn = psycopg2.connect(DB_URL) | |
| conn.autocommit = True | |
| def home(): | |
| return {"status": "Backend running π"} | |
| # ----------------------- | |
| # SIGNUP | |
| # ----------------------- | |
| async def signup(req: Request): | |
| data = await req.json() | |
| name = data.get("name") | |
| email = data.get("email") | |
| password = data.get("password") | |
| country = data.get("country") | |
| cur = conn.cursor() | |
| # check user exists | |
| cur.execute("SELECT email FROM users WHERE email=%s", (email,)) | |
| if cur.fetchone(): | |
| return {"message": "User already exists"} | |
| # insert user | |
| cur.execute(""" | |
| INSERT INTO users (name, email, password, country) | |
| VALUES (%s, %s, %s, %s) | |
| """, (name, email, password, country)) | |
| return {"message": "User created successfully"} | |
| # ----------------------- | |
| # LOGIN | |
| # ----------------------- | |
| async def login(req: Request): | |
| data = await req.json() | |
| email = data.get("email") | |
| password = data.get("password") | |
| cur = conn.cursor() | |
| cur.execute(""" | |
| SELECT id, name, email, country | |
| FROM users | |
| WHERE email=%s AND password=%s | |
| """, (email, password)) | |
| user = cur.fetchone() | |
| if user: | |
| return { | |
| "message": "Login success", | |
| "user": { | |
| "id": user[0], | |
| "name": user[1], | |
| "email": user[2], | |
| "country": user[3] | |
| } | |
| } | |
| return {"message": "Invalid credentials"} |