附上代碼:
import hashlib
import re
from pydantic import BaseModel#, EmailStr
from typing import Union
from fastapi import FastAPI, HTTPException
from deta import Deta
app = FastAPI()
deta = Deta("a0160j9a_AuyhDiXyZgZRVjUKH92jizzgCQRT8sy5")
users = deta.Base("users")
def is_email(email: str) -> bool:
if re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$', email):
return True
return False
class RegisterInput(BaseModel):
username: str
password: str
email: str
class LoginInput(BaseModel):
username: str
password: str
@app.get("/")
def home():
return {
"message":"welcome"
}
@app.post("/register")
async def register(input: RegisterInput):
if not is_email(input.email):
raise HTTPException(status_code=400, detail="Invalid email")
hashed_password = hashlib.sha256(input.password.encode()).hexdigest()
await users.put({"username": input.username, "email": input.email, "hashed_password": hashed_password})
return {"message": "Successfully registered"}
@app.post("/login")
async def login(input: LoginInput):
hashed_password = hashlib.sha256(input.password.encode()).hexdigest()
result = await users.query({"username": input.username}).get()
if not result:
raise HTTPException(status_code=400, detail="Incorrect username or password")
if result["hashed_password"] != hashed_password:
raise HTTPException(status_code=400, detail="Incorrect username or password")
return {"message": "Successfully logged in"}
有許多問題搞不懂,然後不知道該如何著手。