| 1 | from typing import Any, List |
| 2 | |
| 3 | from asgiref.sync import iscoroutinefunction, sync_to_async |
| 4 | from django.conf import settings |
| 5 | from django.http import HttpRequest |
| 6 | from django.utils.decorators import sync_and_async_middleware |
| 7 | |
| 8 | from ninja.conf import settings as ninja_settings |
| 9 | from ninja.params.models import FileModel |
| 10 | |
| 11 | FIX_MIDDLEWARE_PATH: str = "ninja.compatibility.files.fix_request_files_middleware" |
| 12 | FIX_METHODS = ninja_settings.FIX_REQUEST_FILES_METHODS |
| 13 | |
| 14 | |
| 15 | def need_to_fix_request_files(methods: List[str], params_models: List[Any]) -> bool: |
| 16 | has_files_params = any( |
| 17 | issubclass(model_class, FileModel) for model_class in params_models |
| 18 | ) |
| 19 | method_needs_fix = bool(set(methods) & FIX_METHODS) |
| 20 | middleware_installed = FIX_MIDDLEWARE_PATH in settings.MIDDLEWARE |
| 21 | return has_files_params and method_needs_fix and not middleware_installed |
| 22 | |
| 23 | |
| 24 | @sync_and_async_middleware |
| 25 | def fix_request_files_middleware(get_response: Any) -> Any: |
| 26 | """ |
| 27 | This middleware fixes long historical Django behavior where request.FILES is only |
| 28 | populated for POST requests. |
| 29 | https://code.djangoproject.com/ticket/12635 |
| 30 | """ |
| 31 | if iscoroutinefunction(get_response): |
| 32 | |
| 33 | async def async_middleware(request: HttpRequest) -> Any: |
| 34 | if ( |
| 35 | request.method in FIX_METHODS |
| 36 | and request.content_type != "application/json" |
| 37 | ): |
| 38 | initial_method = request.method |
| 39 | request.method = "POST" |
| 40 | request.META["REQUEST_METHOD"] = "POST" |
| 41 | await sync_to_async(request._load_post_and_files)() |
| 42 | request.META["REQUEST_METHOD"] = initial_method |
| 43 | request.method = initial_method |
| 44 | |
| 45 | return await get_response(request) |
| 46 | |
| 47 | return async_middleware |
| 48 | else: |
| 49 | |
| 50 | def sync_middleware(request: HttpRequest) -> Any: |
| 51 | if ( |
| 52 | request.method in FIX_METHODS |
| 53 | and request.content_type != "application/json" |
| 54 | ): |
| 55 | initial_method = request.method |
| 56 | request.method = "POST" |
| 57 | request.META["REQUEST_METHOD"] = "POST" |
| 58 | request._load_post_and_files() |
| 59 | request.META["REQUEST_METHOD"] = initial_method |
| 60 | request.method = initial_method |
| 61 | |
| 62 | return get_response(request) |
| 63 | |
| 64 | return sync_middleware |