Skip to content

Instantly share code, notes, and snippets.

@allen-munsch
Created July 10, 2020 02:00
Show Gist options
  • Save allen-munsch/6c224bc913ba8c23eaf1d98aec24068a to your computer and use it in GitHub Desktop.
Save allen-munsch/6c224bc913ba8c23eaf1d98aec24068a to your computer and use it in GitHub Desktop.
fastapi, starlette middleware wrapper for existing django middleware [broken]
from uuid import uuid4
from django.http import HttpRequest, QueryDict
from django.middleware.csrf import CSRF_SESSION_KEY
from django.utils.datastructures import MultiValueDict
from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from api.logs import setup_logging, ASGILoggingMiddleware
from pm.wsgi import application
from api.routes import api_v2
from django.conf import settings
import traceback
import importlib
middleware = []
for path in settings.MIDDLEWARE:
path = path.split('.')
middleware_class = path.pop()
middleware_module = importlib.import_module('.'.join(path))
middleware.append(getattr(middleware_module, middleware_class))
class DjangoMiddlewareWrapper(BaseHTTPMiddleware):
'''
An attempt to write a wrapper for django wsgi middlewares for starlette fastapi
getting into the weeds with this, and it looks like the request object has so many things set
on it within the django universe, that it looks pretty difficult to do within a FastAPI middleware
if anyone has any ideas on this i'd be interested in knowing about them
'''
async def dispatch(self, request, call_next):
instantiated_classes = []
# from django.http.request.HttpRequest
request.META = {}
request.GET = QueryDict(mutable=True)
request.POST = QueryDict(mutable=True)
request.COOKIES = {}
request.META = {}
request.FILES = MultiValueDict()
request.path = request.scope.get('path')
request.path_info = ''
request.resolver_match = None
request.content_type = None
request.content_params = None
import pdb;pdb.set_trace()
for middleware_class in middleware:
m = middleware_class()
instantiated_classes.append(m)
if hasattr(m, 'process_request'):
#########################################
# errors out on trying to set request.session :'(
# within the django.contrib.sessions.middleware.SessionMiddleware
#########################################
m.process_request(request)
response = await call_next(request)
for m in instantiated_classes:
if hasattr(m, 'process_response'):
response = m.process_response(request, response)
return response
asgi_app = FastApi()
asgi_app.add_middleware(SessionMiddleware)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment