graphql-python / graphene-django

Build powerful, efficient, and flexible GraphQL APIs with seamless Django integration.
http://docs.graphene-python.org/projects/django/en/latest/
MIT License
4.28k stars 766 forks source link

Middlewares are executing in reverse order #1499

Open tbhaxor opened 9 months ago

tbhaxor commented 9 months ago

I am integrating it with the Django and middleware list is not obeying the ascending order of the list. I have to add [::-1] to make it coherent.

Create two middleware and add print statements in it. 1st indexed middleware will execute first and then followed by 0th index middleware

GRAPHENE = {
    "SCHEMA": "backend.graphql.schema",
    "MIDDLEWARE": [
        "backend.graphql.DebugMiddleware",
        "backend.graphql.RequestAuthInjectorMiddleware",
    ],
}

These two middlewares are defined as following

class RequestAuthInjectorMiddleware:
    def resolve(self, next, root, info, **kwargs):
        print("Request Auth Injector")
        return next(root, info, **kwargs)

class DebugMiddleware(DjangoDebugMiddleware):
    def resolve(self, next, root, info, *args, **kwargs):
        print("Debug Middleware")
        return super().resolve(next, root, info, **kwargs)

Output

Request Auth Injector
Debug Middleware

It should run the middleware in same order as provided in the list. For example, here is the hotfix

GRAPHENE = {
    "SCHEMA": "viewgur_backend.graphql.schema",
    "MIDDLEWARE": [
        "viewgur_backend.graphql.DebugMiddleware",
        "viewgur_backend.graphql.RequestAuthInjectorMiddleware",
-    ],
+    ][::-1],
}

And now the output will be accurate

Debug Middleware
Request Auth Injector

It is confusing to anyone newbie (like I was just few mins ago) to find out the apparent nature

gencurrent commented 7 months ago

@tbhaxor Perhaps the issue is referred to graphene-django, isn't it?