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

aiohttp middleware and replacing a request in flight #3097

Closed
jerblack opened this issue Jun 21, 2018 · 6 comments
Closed

aiohttp middleware and replacing a request in flight #3097

jerblack opened this issue Jun 21, 2018 · 6 comments
Labels

Comments

@jerblack
Copy link

jerblack commented Jun 21, 2018

Hi, I am trying to build a middleware that attempts to automatically add slashes to the end of uris that are missing them to avoid having to double-define all my routes with and without a trailing slash to ensure no one 404s. I saw your normalize_path_middleware and started with that, but I can't use anything that's going to force a redirect on the client. I need to be able to accomplish the same thing entirely on the server side.

Here's my attempt at that middleware, which just clones the request with a new rel_url and passes that along, but I still am getting 404s when I don't include a trailing backslash in my uris. Any ideas? Thanks.

from aiohttp.web_urldispatcher import SystemRoute

def middleware(f):
    f.__middleware_version__ = 1
    return f

def trailing_slashes():
    @middleware
    async def impl(request, handler):
        if isinstance(request.match_info.route, SystemRoute):
            rel_url = str(request.rel_url)
            if '?' in rel_url:
                path, query = rel_url.split('?', 1)
                query = f'?{query}'
            else:
                path = rel_url
                query = ''
            if not path.endswith('/'):
                rel_url = f'{path}/{query}'
                request = request.clone(rel_url=rel_url)

        return await handler(request)

    return impl

And here is a sample class that implements it.

from aiohttp import web
import slashes_mw

class ClassName(object):
    def __init__(self):
        self.app = web.Application(middlewares=[slashes_mw.trailing_slashes()])
        self.app.add_routes(self.get_routes())
        web.run_app(self.app, port=80, host='0.0.0.0')

    def get_routes(self):
        return [
            web.get('/', self.handler),
            web.get('/{name}/', self.handler)
        ]

    def handler(self, request):
        return web.Response(text='hello')

ClassName()
@asvetlov
Copy link
Member

asvetlov commented Jun 21, 2018 via email

@jerblack
Copy link
Author

It's not a site, it's an API that will be exposed to IoT devices that won't be able to redirect to another url.

@asvetlov
Copy link
Member

I see nothing bad with registering a handler twice than.
It works faster than middleware processing BTW.

@jerblack
Copy link
Author

Can I get a yes or no answer on whether or not the technical question I am asking is possible?

@asvetlov
Copy link
Member

Well, if you insist.
You need to call app.router.resolve() to find a new match_info and call a new handler.
Not sure if there are no pitfalls (another middlewares for a new route, API forward compatibility etc) -- it touches a private API.
Anyway reading https://github.com/aio-libs/aiohttp/blob/master/aiohttp/web_app.py#L313-L352 can help you to master something.

@lock
Copy link

lock bot commented Oct 28, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a [new issue] for related bugs.
If you feel like there's important points made in this discussion, please include those exceprts into that [new issue].
[new issue]: https://github.com/aio-libs/aiohttp/issues/new

@lock lock bot added the outdated label Oct 28, 2019
@lock lock bot locked as resolved and limited conversation to collaborators Oct 28, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants