本文介绍了是否可以将 FastAPI 与 Django 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名 Django 开发人员,最近偶然发现了 FastAPI 框架.

I'm a Django developer and recently stumbled onto the FastAPI framework.

然后我决定试一试.但通常当您谈论使用 Django 构建 RESTful API 时,您通常会使用 Django Rest Framework (DRF).

Then I decided to give it a shot. But usually when you talk about building RESTful APIs with Django you usually use the Django Rest Framework (DRF).

是否有人知道是否可以使用 Django 特权(例如 ORM)用 FastAPI 替换 DRF,并且仍然可以访问 FastAPI 的所有 async 功能?

Is anybody aware if it is possible to substitute DRF by FastAPI using Django perks, like its ORM, and still have access to all of FastAPI's async features?

到目前为止,我只找到了一篇关于此的文章.但是在集成的过程中作者失去了FastAPI的大部分功能.您可以在这里找到.

Up until now I only found one article on this. But in the process of integration the author lost most of the features of FastAPI.You can find it here.

在 FastAPI 文档中,他们确实提到可以将某些请求重定向到 WSGI 应用程序 here.

In the FastAPI docs, they do mention that it is possible to redirect certain request to a WSGI application here.

推荐答案

简短回答

是的,可以使用 WSGIMiddleware.

例如,您可以使用所有 Django 功能 (也是管理员) 使用此示例代码进行挂载.

import os
from importlib.util import find_spec

from configurations.wsgi import get_wsgi_application
from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
from fastapi.staticfiles import StaticFiles

from api import router

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
os.environ.setdefault("DJANGO_CONFIGURATIN", "Localdev")

application = get_wsgi_application()

app = FastAPI()
app.mount("/admin", WSGIMiddleware(application))
app.mount("/static"
    StaticFiles(
         directory=os.path.normpath(
              os.path.join(find_spec("django.contrib.admin").origin, "..", "static")
         )
   ),
   name="static",
)

这个也来自 WSGIMiddleware 文档,这是一个更直接的例子(这个是针对 Flask 的,但它展示了相同的想法.).

Also this one is from WSGIMiddleware documentation, it's a more straight-forward example (This one is for Flask but it demonstrates the same idea.).

from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
from flask import Flask, escape, request

flask_app = Flask(__name__)


@flask_app.route("/")
def flask_main():
    name = request.args.get("name", "World")
    return f"Hello, {escape(name)} from Flask!"


app = FastAPI()


@app.get("/v2")
def read_main():
    return {"message": "Hello World"}


app.mount("/v1", WSGIMiddleware(flask_app))

这篇关于是否可以将 FastAPI 与 Django 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 04:36