FastAPI与Django ORM集成项目技术文档
fastapi-django FastAPI with Django ORM 项目地址: https://gitcode.com/gh_mirrors/fa/fastapi-django
安装指南
环境准备
- 确保已安装Python 3.7+。
- 安装Poetry包管理工具:
curl -sSL https://install.python-poetry.org | python3 -
项目安装
- 克隆项目到本地:
git clone https://github.com/yourusername/fastapi-django.git cd fastapi-django
- 使用Poetry安装依赖:
poetry install
项目使用说明
数据库迁移
在首次运行项目之前,需要进行数据库迁移:
./manage.py migrate
数据插入
可以通过Django shell插入初始数据:
./manage.py shell
在shell中执行以下Python代码:
from polls.models import Choice, Question
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
运行项目
- 启动FastAPI应用:
uvicorn mysite.asgi:fastapp --reload
- 启动Django应用:
uvicorn mysite.asgi:application --port 8001 --reload
- 生成Django管理界面的静态文件:
./manage.py collectstatic --noinput
访问项目
- FastAPI文档:
http://localhost:8000/docs
- Django管理界面:
http://localhost:8001/admin
项目API使用文档
获取问题列表
- URL:
/question/
- 方法:
GET
- 响应:
{ "items": [ { "question_text": "What's new?", "pub_date": "2021-03-29T04:18:54.724432+00:00" } ] }
其他API
更多API请参考FastAPI自动生成的文档:http://localhost:8000/docs
。
项目安装方式
目录结构
.
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── polls
├── __init__.py
├── adapters
│ └── __init__.py
├── admin.py
├── apps.py
├── migrations
│ ├── 0001_initial.py
│ └── __init__.py
├── models
│ └── __init__.py
├── routers
│ ├── __init__.py
│ ├── choices.py
│ └── questions.py
├── schemas
│ └── __init__.py
└── tests.py
关键目录说明
models
: 存放Django ORM模型。routers
: 存放FastAPI路由。schemas
: 存放Pydantic模型。adapters
: 用于将Django ORM模型转换为Pydantic模型。
配置Django应用
在mysite/settings.py
中配置是否挂载Django应用:
MOUNT_DJANGO_APP = True
工具
- FastAPI文档:
http://localhost:8000/docs
- Django管理界面:
http://localhost:8001/admin
- Pre-commit钩子:
pre-commit install pre-commit run --all-files
通过以上步骤,您可以顺利安装并运行fastapi-django
项目,并使用其提供的API和功能。
fastapi-django FastAPI with Django ORM 项目地址: https://gitcode.com/gh_mirrors/fa/fastapi-django
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考