fastapi框架搭建的python项目,实现链接数据库,实现用户的登录和注册

好的,下面是重新整理后的完整实现,包含你的 database.py 配置。

1. 安装依赖

确保安装了 FastAPI, SQLAlchemy, psycopg2-binary, PassLibPyJWT 库:

pip install fastapi sqlalchemy psycopg2-binary passlib[bcrypt] pyjwt

2. 配置数据库

app/core/config.py

class Settings:
    DATABASE_URL = "postgresql://user:password@localhost/dbname"

settings = Settings()

app/db/database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings

engine = create_engine(settings.DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

3. 定义模型

app/db/models.py

from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, index=True)
    userId = Column(String, unique=True, index=True, nullable=False)
    userName = Column(String, index=True, nullable=False)
    password = Column(String, nullable=False)
    createTime = Column(DateTime, default=datetime.utcnow)
    updateTime = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    deleted = Column(Boolean, default=False)

4. 创建数据库表

app/main.py

from fastapi import FastAPI
from app.db.database import engine
from app.db import models
from app.routers import auth

app = FastAPI()

models.Base.metadata.create_all(bind=engine)

app.include_router(auth.router, prefix="/auth", tags=["auth"])

5. 定义 Pydantic 模式

app/db/schemas.py

from pydantic import BaseModel

class UserCreate(BaseModel):
    userId: str
    userName: str
    password: str

class UserLogin(BaseModel):
    userId: str
    password: str

6. 实现用户注册和登录

app/routers/auth.py

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from jose import JWTError, jwt
from datetime import datetime, timedelta

from app.db import models, schemas
from app.db.database import get_db

router = APIRouter()

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "secret"  # 请使用更复杂的密钥
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
    return pwd_context.hash(password)

def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

@router.post("/register", response_model=schemas.UserCreate)
def register_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.userId == user.userId).first()
    if db_user:
        raise HTTPException(status_code=400, detail="User ID already registered")
    hashed_password = get_password_hash(user.password)
    db_user = models.User(userId=user.userId, userName=user.userName, password=hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@router.post("/login")
def login_user(user: schemas.UserLogin, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.userId == user.userId).first()
    if not db_user:
        raise HTTPException(status_code=400, detail="Invalid user ID or password")
    if not verify_password(user.password, db_user.password):
        raise HTTPException(status_code=400, detail="Invalid user ID or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": db_user.userId}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

7. 注册路由

app/main.py

from fastapi import FastAPI
from app.db.database import engine
from app.db import models
from app.routers import auth

app = FastAPI()

models.Base.metadata.create_all(bind=engine)

app.include_router(auth.router, prefix="/auth", tags=["auth"])

项目结构

.
├── app
│   ├── core
│   │   ├── config.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   ├── db
│   │   ├── database.py
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── __pycache__
│   │   └── schemas.py
│   ├── __init__.py
│   ├── main.py
│   ├── __pycache__
│   ├── routers
│   │   ├── auth.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   ├── schemas
│   │   └── __init__.py
│   ├── services
│   │   ├── __init__.py
│   │   └── __pycache__
│   └── utils
│       └── __init__.py
├── README.md
├── requirements.txt
├── run.py
├── tests
│   ├── __init__.py
│   └── test_main.http

现在,你可以运行你的 FastAPI 应用,并使用 /auth/register 路由进行用户注册,使用 /auth/login 路由进行登录并获取 JWT token。

要调用上面的代码,首先需要确保 FastAPI 应用已正确配置并运行。以下是调用该应用的一些步骤和示例:

1. 确保项目结构正确

确保项目结构与以下一致:

.
├── app
│   ├── core
│   │   ├── config.py
│   │   ├── __init__.py
│   └── db
│       ├── database.py
│       ├── models.py
│       ├── schemas.py
│   ├── main.py
│   ├── routers
│       ├── auth.py
│   └── __init__.py
├── README.md
├── requirements.txt
├── run.py
├── tests
│   └── test_main.http

2. 编写启动脚本

编写一个启动脚本 run.py,用于运行 FastAPI 应用。

# run.py
import uvicorn

if __name__ == "__main__":
    uvicorn.run("app.main:app", host="127.0.0.1", port=8000, reload=True)

3. 启动应用

在终端中运行以下命令启动 FastAPI 应用:

python run.py

此时,FastAPI 应用将运行在 http://127.0.0.1:8000

4. 调用 API 进行用户注册和登录

可以使用 HTTP 客户端工具(如 curl 或 Postman)调用 API 进行用户注册和登录。

使用 curl 命令行工具

用户注册

curl -X POST "http://127.0.0.1:8000/auth/register" -H "Content-Type: application/json" -d '{
  "userId": "testuser",
  "userName": "Test User",
  "password": "testpassword"
}'

用户登录

curl -X POST "http://127.0.0.1:8000/auth/login" -H "Content-Type: application/json" -d '{
  "userId": "testuser",
  "password": "testpassword"
}'
使用 Postman 工具

用户注册

  1. 打开 Postman。
  2. 创建一个新的 POST 请求,URL 为 http://127.0.0.1:8000/auth/register
  3. 在 Headers 中添加 Content-Type: application/json
  4. 在 Body 中选择 raw 并粘贴以下 JSON 数据:
    {
      "userId": "testuser",
      "userName": "Test User",
      "password": "testpassword"
    }
    
  5. 点击 Send 按钮发送请求。

用户登录

  1. 创建一个新的 POST 请求,URL 为 http://127.0.0.1:8000/auth/login
  2. 在 Headers 中添加 Content-Type: application/json
  3. 在 Body 中选择 raw 并粘贴以下 JSON 数据:
    {
      "userId": "testuser",
      "password": "testpassword"
    }
    
  4. 点击 Send 按钮发送请求。

5. 测试和验证

可以编写测试文件来测试 API。

tests/test_main.http

### 用户注册
POST http://127.0.0.1:8000/auth/register
Content-Type: application/json

{
  "userId": "testuser",
  "userName": "Test User",
  "password": "testpassword"
}

### 用户登录
POST http://127.0.0.1:8000/auth/login
Content-Type: application/json

{
  "userId": "testuser",
  "password": "testpassword"
}

在你的 IDE(如 PyCharm 或 VS Code)中使用 HTTP 客户端工具执行这些 HTTP 请求文件,验证 API 是否正常工作。

通过这些步骤,你应该能够成功调用上面的代码,实现用户注册和登录功能并获取 JWT token。

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MonkeyKing.sun

对你有帮助的话,可以打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值