Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for middleware as: func(request, next) #1789

Closed
wants to merge 4 commits into from

Conversation

protibimbok
Copy link

Add support for per route middleware

Route Middlewares

The route middlewares behaves more like an endpoint than a middleware.
These middlewares receive two parameters request: Request and next: async function

async def check_admin(request: Request, next):
    if request.headers['Authorization'] == 'I am admin':
        request.isAdmin = True
        request.perms = ['a', 'b', 'c']
        return await next()
    else:
        return JSONResponse({'error':'Unauthorized access'})


async def check_perm(request: Request, next):
    if request.isAdmin and 'c' in request.perms:
        response = await next() # you can now do stuff with the response
        if type(response) == str:
            response = Response(response, media_type="text/plain")
        elif type(response) == dict:
            response = JSONResponse(response)

        return response
    else:
        return JSONResponse({'error':'Unauthorized access'})



routes = [
    Route("/admin", endpoint = admin_page, middlewares = check_admin),
    Route(
        "/admin/secret", endpoint = admin_secret,
        middlewares = [check_admin, check_perm] # Middlewares will be ran in the same order
    )
]

@Kludex
Copy link
Member

Kludex commented Aug 4, 2022

Thanks for the PR!

Also, this PR is more complex, and breaks how we propose to structure Starlette: blocks of ASGI applications.

For that reason, I'll be closing this PR.

@Kludex Kludex closed this Aug 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants