AttributeError: 'coroutine' object has no attribute 'status_code'

This is error message

Traceback (most recent call last):
File "myenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/myenv/lib/python3.9/site-packages/django/utils/deprecation.py", line 136, in __call__
response = self.process_response(request, response)
File "/myenv/lib/python3.9/site-packages/django/middleware/common.py", line 107, in process_response
if response.status_code == 404 and self.should_redirect_with_slash(request):
AttributeError: 'coroutine' object has no attribute 'status_code'

This middleware function im using

class CustomCorsAllowOrigin(MiddlewareMixin):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        allowed_origin_list = ['https://desktop.digital.com','com.liqvd.digital','com.digital.ios','com.liqvd.digital.dev','com.liqvd.digital.test']

        actual_apps_referer = request.headers.get('Referer','')

        desktop_referer = request.headers.get('referrer','')

        chrome_extension_referer = request.headers.get('x-request-referrer','')

        if actual_apps_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = actual_apps_referer

        if chrome_extension_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = chrome_extension_referer

        if desktop_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = desktop_referer

        return response

When i run asgi application getting error

It seems to me like your middleware isn’t properly set up to handle async views.

Your middleware is inheriting from MiddlewareMixin, which does a lot more in it’s __init__ method that you’ve defined, including checking to see if get_response is an async function.

I’d suggest removing your __init__ method and allowing the mixin’s __init__ method do its thing. This probably also implies that you’ll need to do a custom __acall__ method as well.

Either that, or flag your middleware as async_capable = False and force this middleware to execute in a sync context.

(I might also suggest you review the code in the MiddlewareMixin to see what it’s doing, and how.)

i tried this also gettng same error

@sync_and_async_middleware
class CustomCorsAllowOrigin:

    def __init__(self, get_response):
        self.get_response = get_response

    async def __acall__(self, request):
        # Await get_response if it's an async function
        if asyncio.iscoroutinefunction(self.get_response):
            response = await self.get_response(request)
        else:
            response = self.get_response(request)

        # Await the response if it's still a coroutine
        if asyncio.iscoroutine(response):
            response = await response

        # Ensure the response is a resolved HttpResponse object
        if not isinstance(response, HttpResponse):
            raise TypeError(f"Expected HttpResponse but got {type(response)}")

        # Define allowed origins
        allowed_origin_list = [
            'https://desktop.digital.com',
            'com.liqvd.digital',
            'com.digital.ios',
            'com.liqvd.digital.dev',
            'com.liqvd.digital.test'
        ]

        # Get referer headers
        actual_apps_referer = request.headers.get('Referer', '')
        desktop_referer = request.headers.get('referrer', '')
        chrome_extension_referer = request.headers.get('x-request-referrer', '')

        # Set CORS headers based on referer
        if actual_apps_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = actual_apps_referer
        elif chrome_extension_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = chrome_extension_referer
        elif desktop_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = desktop_referer

        return response

This is what I suggested:

This means supplying both your custom __call__ and __acall__ methods in addition to removing your __init__ method, while still inheriting from that mixin.

if i remove init method getting this error

Traceback (most recent call last):
  File "/myenv/bin/daphne", line 8, in <module>
    sys.exit(CommandLineInterface.entrypoint())
  File "/myenv/lib/python3.9/site-packages/daphne/cli.py", line 171, in entrypoint
    cls().run(sys.argv[1:])
  File "/myenv/lib/python3.9/site-packages/daphne/cli.py", line 233, in run
    application = import_by_path(args.application)
  File "/myenv/lib/python3.9/site-packages/daphne/utils.py", line 17, in import_by_path
    target = importlib.import_module(module_path)
  File "/.pyenv/versions/3.9.19/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/./asgi.py", line 30, in <module>
    "http": get_asgi_application(),
  File "/myenv/lib/python3.9/site-packages/django/core/asgi.py", line 13, in get_asgi_application
    return ASGIHandler()
  File "/myenv/lib/python3.9/site-packages/django/core/handlers/asgi.py", line 146, in __init__
    self.load_middleware(is_async=True)
  File /myenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 61, in load_middleware
    mw_instance = middleware(adapted_handler)
TypeError: CustomCorsAllowOrigin() takes no arguments

Please post your current code.

@sync_and_async_middleware
class CustomCorsAllowOrigin:

    async def __acall__(self, request):
        # Ensure the response is resolved before returning
        response = await self._resolve_response(request)

        # Verify the response type
        if not isinstance(response, HttpResponse):
            raise TypeError(f"Expected HttpResponse but got {type(response)}")

        # Define allowed origins
        allowed_origin_list = [
            'https://desktop.digiboxx.com',
            'com.liqvd.digibox',
            'com.digiboxx.ios',
            'com.liqvd.digibox.dev',
            'com.liqvd.digibox.test'
        ]

        # Get referer headers
        actual_apps_referer = request.headers.get('Referer', '')
        desktop_referer = request.headers.get('referrer', '')
        chrome_extension_referer = request.headers.get('x-request-referrer', '')

        # Set CORS headers based on referer
        if actual_apps_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = actual_apps_referer
        elif chrome_extension_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = chrome_extension_referer
        elif desktop_referer in allowed_origin_list:
            response['Access-Control-Allow-Origin'] = desktop_referer

        return response

    async def _resolve_response(self, request):
        """
        Helper function to ensure the response is fully resolved.
        """
        # Get the response, await if necessary
        if asyncio.iscoroutinefunction(self.get_response):
            response = await self.get_response(request)
        else:
            response = self.get_response(request)

        # If the response is still a coroutine, resolve it
        if asyncio.iscoroutine(response):
            response = await response

        return response

You still didn’t do what I suggested.

The __acall__ method is called by the __call__ method in the MiddlewareMixin class. It’s not something that is part of the middleware api.

I suggest you go back to the docs for Middleware / Asynchronous support, and read the source code of the MiddlewareMixin, to see everything that you need to do to enable async support in your middleware class.

Thanks for help its working now