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

Improve type annotations in routes.py #566

Open
amotl opened this issue Oct 30, 2024 · 0 comments
Open

Improve type annotations in routes.py #566

amotl opened this issue Oct 30, 2024 · 0 comments

Comments

@amotl
Copy link
Collaborator

amotl commented Oct 30, 2024

@coderabbitai mentioned at #560 (comment):

It appears that the type annotations I suggested for apps are causing mypy to raise errors because app can be either an ASGI application (awaitable) or a WSGI application (non-awaitable). This leads to type inconsistencies when attempting to await app(scope, receive, send).

To address this, we can adjust the type annotations to accurately reflect the possible types of app and modify the code to handle both cases explicitly. Here's a revised approach:

  1. Update the type annotations:

    from typing import Union, Callable, Awaitable, Any
    
    ASGIApp = Callable[[dict, Callable, Callable], Awaitable[None]]
    WSGIApp = Callable[..., Any]  # WSGI applications accept 'environ' and 'start_response'
    
    apps: t.Dict[str, Union[ASGIApp, WSGIApp]]
  2. Modify the __call__ method to handle both ASGI and WSGI apps:

    async def __call__(self, scope, receive, send):
        # ... existing code ...
    
        # Call into a submounted app, if one exists.
        for path_prefix, app in self.apps.items():
            if path.startswith(path_prefix):
                scope["path"] = path[len(path_prefix) :]
                scope["root_path"] = root_path + path_prefix
                if asyncio.iscoroutinefunction(app):
                    # ASGI application
                    await app(scope, receive, send)
                else:
                    # WSGI application
                    app = WSGIMiddleware(app)
                    await app(scope, receive, send)
                return
    
        # ... existing code ...

This way, we explicitly check if app is an awaitable ASGI application or a regular WSGI application and handle each case accordingly. This should resolve the mypy errors by ensuring type consistency.

Let me know if this helps or if you have further questions.

(\_ _/)
( •_• )
/ >💭< \

Originally posted by @coderabbitai[bot] in #560 (comment)

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

No branches or pull requests

1 participant