commit
7bd182a61c
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,14 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
# 数据库连接字符串
|
||||
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:mypassword12@127.0.0.1:3306/lianai"
|
||||
|
||||
# 创建数据库引擎
|
||||
engine = create_engine(SQLALCHEMY_DATABASE_URL)
|
||||
|
||||
# 创建会话本地类
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# 声明基类
|
||||
Base = declarative_base()
|
@ -0,0 +1,70 @@
|
||||
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)
|
@ -0,0 +1,11 @@
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from database import Base
|
||||
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
username = Column(String(30),index=True,primary_key=True)
|
||||
password = Column(String(100), index=True,nullable=False)
|
||||
|
||||
|
Loading…
Reference in new issue