0

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)

  • Start by finding out _why_ your current application is slow - FastAPI doesn't make stuff magically faster - to make stuff go faster, do less - which means that you might not need every magical thing that django offers you. But if you want to do the exact same thing, just wrapped in a different framework, you should at least know first where the slowness comes from. You can also run django in async mode, but it all depends on what's causing your slowness: https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ – MatsLindh Aug 14 '23 at 13:41

1 Answers1

1

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

EdgarAlejandro
  • 347
  • 1
  • 15