You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.7 KiB

1 week ago
from fastapi import FastAPI, Depends, HTTPException, Request
from database import engine, SessionLocal
from models import User
from sqlalchemy.orm import Session
import uvicorn
from models import User
app = FastAPI()
# 创建所有表
User.metadata.create_all(bind=engine)
# 依赖注入:获取数据库会话
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/login")
async def login(request: Request, db: Session = Depends(get_db)):
user_data =await request.json()
print(user_data)
user=db.query(User).filter(User.username==user_data['username']).first()
if user:
if user.password==user_data['password']:
return {"code":200,"msg":"登录成功"}
else:
return {"code":400,"msg":"密码错误"}
return {"code":501,"msg":"账号不存在"}
@app.post("/register")
async def register(request: Request, db: Session = Depends(get_db)):
user_data =await request.json()
users=db.query(User).filter(User.username==user_data['username']).first()
if users:
return {"code":501,"msg":"账号已存在"}
else:
new_user=User(username=user_data['username'],password=user_data['password'])
db.add(new_user)
db.commit()
db.refresh(new_user)
print(new_user)
return {"code":200,"msg":"注册成功"}
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
if __name__ == '__main__':
# 运行fastapi程序
uvicorn.run(app="main:app", host="127.0.0.1", port=8000, reload=True)