How can make api using fastapi for django project

397 views Asked by At

I want my projects to be more faster and i decided to use fastapi for them.But can't import my django models and form to fastapi.can someone help me to make api using fastapi for django projects?

any code? (for example blog project)

1

There are 1 answers

0
EdgarAlejandro On

It is possible, the quick way is:

you must have fastapi and django installed in the same environment.

The Django settins must be connected with your database and in fastAPI:

# main.py
import os
from fastapi import FastAPI
from your_django_project_name import settings as django_settings

os.environ['DJANGO_SETTINGS_MODULE'] = 'django_settings'
import django
django.setup()

app = FastAPI()

and after that, you have access:

from your_django_app_name.models import Blog

@app.get("/blogs/")
async def get_blogs():
    blogs = Blog.objects.all()
    return {"blogs": [blog.title for blog in blogs]}

To ensure the conection you must create a FastAPI Middleware

from fastapi.middleware.base import BaseHTTPMiddleware
from django import db

class DBConnectionMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        db.connections["default"].ensure_connection()
        response = await call_next(request)
        db.connections["default"].close()
        return response

app.add_middleware(DBConnectionMiddleware)

PD: what @MatsLindh said is true, find out first what is the problem that makes it slow