如何在Django项目中使用FastAPI开发API?求模型导入方案及示例代码
在Django项目中集成FastAPI开发API(博客示例)
核心思路
要让FastAPI能访问Django的模型和表单,关键是在FastAPI启动时初始化Django运行环境,否则无法加载Django的配置和ORM模型。
1. 项目结构示例
假设你的Django博客项目结构如下:
myblog/ ├── myblog/ # Django项目配置目录 │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── blog/ # 博客应用 │ ├── __init__.py │ ├── models.py # Django模型 │ ├── forms.py # Django表单 │ └── admin.py └── main.py # FastAPI入口文件
2. 初始化Django环境(FastAPI入口)
在main.py中先配置Django环境,之后就能正常导入模型和表单:
import os import django from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List # 配置Django环境变量,指向项目settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myblog.settings") django.setup() # 现在可以导入Django的模型和表单了 from blog.models import Post from blog.forms import PostForm app = FastAPI(title="Django + FastAPI Blog API")
3. 定义Pydantic数据模型
FastAPI依赖Pydantic做数据校验和序列化,需对应Django模型定义Schema:
class PostBase(BaseModel): title: str content: str author: str # 创建文章时的请求模型 class PostCreate(PostBase): pass # 返回给前端的响应模型 class PostResponse(PostBase): id: int created_at: str class Config: orm_mode = True # 允许直接从Django ORM对象转换为响应模型
4. 实现API CRUD接口
示例1:基础CRUD操作
# 获取所有文章 @app.get("/posts/", response_model=List[PostResponse]) def get_all_posts(): return Post.objects.all() # 获取单篇文章 @app.get("/posts/{post_id}", response_model=PostResponse) def get_single_post(post_id: int): try: return Post.objects.get(id=post_id) except Post.DoesNotExist: raise HTTPException(status_code=404, detail="Post not found") # 创建文章(直接用Pydantic校验) @app.post("/posts/", response_model=PostResponse) def create_post(post_data: PostCreate): new_post = Post(**post_data.dict()) new_post.save() return new_post
示例2:复用Django表单做验证
如果想复用Django表单的校验逻辑,可以在接口中调用表单的验证方法:
@app.post("/posts/with-form/", response_model=PostResponse) def create_post_with_form(post_data: PostCreate): # 将Pydantic数据转换为表单需要的字典格式 form = PostForm(post_data.dict()) if not form.is_valid(): # 返回表单的错误信息 raise HTTPException(status_code=400, detail=form.errors) # 保存验证后的合法数据 new_post = Post(**form.cleaned_data) new_post.save() return new_post
5. 运行FastAPI
- 安装依赖:
pip install fastapi uvicorn django
- 启动服务:
uvicorn main:app --reload
- 访问自动生成的API文档:
http://127.0.0.1:8000/docs
内容的提问来源于stack exchange,提问作者Daler Ravshanov
相关产品推荐
相关产品推荐

