+
Skip to content

lichunfei369/ShoppingFastAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI登录接口项目

基于FastAPI的用户认证和登录接口实现,提供JWT令牌认证功能。

项目结构

.
├── app/
│   ├── __init__.py          # Python包初始化文件
│   ├── main.py              # FastAPI主应用文件
│   ├── config.py            # 应用配置管理
│   ├── database.py          # 数据库配置和连接
│   ├── models.py            # SQLAlchemy数据模型
│   ├── schemas.py           # Pydantic数据模式
│   ├── crud.py              # 数据库CRUD操作
│   ├── auth.py              # 认证工具函数
│   └── dependencies.py      # FastAPI依赖注入
├── .env                     # 环境变量配置文件
├── Pipfile                  # Pipenv依赖管理文件
└── README.md                # 项目说明文档

功能特性

  • ✅ 用户认证和JWT令牌生成
  • ✅ 密码哈希加密存储
  • ✅ Bearer Token认证
  • ✅ 用户信息获取接口
  • ✅ 数据库模型和CRUD操作
  • ✅ 环境变量配置管理
  • ✅ API文档自动生成

技术栈

  • FastAPI: 现代、快速的Web框架
  • SQLAlchemy: Python SQL工具包和ORM
  • PostgreSQL: 关系型数据库
  • PassLib: 密码哈希库
  • python-jose: JWT令牌处理
  • Pydantic: 数据验证和设置管理
  • Uvicorn: ASGI服务器

安装和运行

1. 安装依赖

# 安装pipenv(如果尚未安装)
pip install pipenv

# 安装项目依赖
pipenv install

# 激活虚拟环境
pipenv shell

2. 配置环境变量

确保 .env 文件中的数据库连接信息正确:

DATABASE_URL=postgresql://username:password@localhost/dbname
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

3. 启动应用

# 使用uvicorn启动开发服务器
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# 或者直接运行main.py
python -m app.main

4. 访问API文档

API端点

POST /login

用户登录接口,返回JWT访问令牌。

请求体:

{
  "username": "user@example.com",
  "password": "yourpassword"
}

响应:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

POST /users/me

获取当前用户信息接口(需要认证)。

请求头:

Authorization: Bearer <access_token>

响应:

{
  "id": 1,
  "email": "user@example.com",
  "is_active": true
}

POST /users/

创建新用户接口。

请求体:

{
  "email": "newuser@example.com",
  "password": "strongpassword123"
}

测试示例

1. 创建用户

curl -X POST "http://localhost:8000/users/" \
     -H "Content-Type: application/json" \
     -d '{
       "email": "test@example.com",
       "password": "testpassword123"
     }'

2. 用户登录

curl -X POST "http://localhost:8000/login" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "username=test@example.com&password=testpassword123"

3. 获取用户信息

curl -X POST "http://localhost:8000/users/me" \
     -H "Authorization: Bearer <your_access_token>"

开发说明

  • 数据库表会在应用启动时自动创建
  • JWT令牌默认30分钟过期
  • 密码使用bcrypt算法加密
  • 所有API端点都有详细的文档和类型注解

安全注意事项

  • 请确保在生产环境中使用强密钥
  • 定期更新依赖包版本
  • 配置适当的CORS策略
  • 使用HTTPS协议传输敏感数据

About

Flutter商城项目后台

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载