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

add types to wsgi module #1018

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 152 additions & 3 deletions uvicorn/_types.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import sys
from typing import Dict, Iterable, Optional, Tuple, Union
from typing import Awaitable, Callable, Dict, Iterable, Optional, Tuple, Type, Union

if sys.version_info < (3, 8):
from typing_extensions import Literal, TypedDict
from typing_extensions import Literal, Protocol, TypedDict
else:
from typing import Literal, TypedDict
from typing import Literal, Protocol, TypedDict


class ASGISpecInfo(TypedDict):
Expand Down Expand Up @@ -65,3 +65,152 @@ class WebsocketScope(TypedDict):

WWWScope = Union[HTTPScope, WebsocketScope]
Scope = Union[HTTPScope, WebsocketScope, LifespanScope]


class HTTPRequestEvent(TypedDict):
type: Literal["http.request"]
body: bytes
more_body: bool


class HTTPResponseStartEvent(TypedDict):
type: Literal["http.response.start"]
status: int
headers: Iterable[Tuple[bytes, bytes]]


class HTTPResponseBodyEvent(TypedDict):
type: Literal["http.response.body"]
body: bytes
more_body: bool


class HTTPServerPushEvent(TypedDict):
type: Literal["http.response.push"]
path: str
headers: Iterable[Tuple[bytes, bytes]]


class HTTPDisconnectEvent(TypedDict):
type: Literal["http.disconnect"]


class WebsocketConnectEvent(TypedDict):
type: Literal["websocket.connect"]


class WebsocketAcceptEvent(TypedDict):
type: Literal["websocket.accept"]
subprotocol: Optional[str]
headers: Iterable[Tuple[bytes, bytes]]


class WebsocketReceiveEvent(TypedDict):
type: Literal["websocket.receive"]
bytes: Optional[bytes]
text: Optional[str]


class WebsocketSendEvent(TypedDict):
type: Literal["websocket.send"]
bytes: Optional[bytes]
text: Optional[str]


class WebsocketResponseStartEvent(TypedDict):
type: Literal["websocket.http.response.start"]
status: int
headers: Iterable[Tuple[bytes, bytes]]


class WebsocketResponseBodyEvent(TypedDict):
type: Literal["websocket.http.response.body"]
body: bytes
more_body: bool


class WebsocketDisconnectEvent(TypedDict):
type: Literal["websocket.disconnect"]
code: int


class WebsocketCloseEvent(TypedDict):
type: Literal["websocket.close"]
code: int
reason: Optional[str]


class LifespanStartupEvent(TypedDict):
type: Literal["lifespan.startup"]


class LifespanShutdownEvent(TypedDict):
type: Literal["lifespan.shutdown"]


class LifespanStartupCompleteEvent(TypedDict):
type: Literal["lifespan.startup.complete"]


class LifespanStartupFailedEvent(TypedDict):
type: Literal["lifespan.startup.failed"]
message: str


class LifespanShutdownCompleteEvent(TypedDict):
type: Literal["lifespan.shutdown.complete"]


class LifespanShutdownFailedEvent(TypedDict):
type: Literal["lifespan.shutdown.failed"]
message: str


ASGIReceiveEvent = Union[
HTTPRequestEvent,
HTTPDisconnectEvent,
WebsocketConnectEvent,
WebsocketReceiveEvent,
WebsocketDisconnectEvent,
LifespanStartupEvent,
LifespanShutdownEvent,
]


ASGISendEvent = Union[
HTTPResponseStartEvent,
HTTPResponseBodyEvent,
HTTPServerPushEvent,
HTTPDisconnectEvent,
WebsocketAcceptEvent,
WebsocketSendEvent,
WebsocketResponseStartEvent,
WebsocketResponseBodyEvent,
WebsocketCloseEvent,
LifespanStartupCompleteEvent,
LifespanStartupFailedEvent,
LifespanShutdownCompleteEvent,
LifespanShutdownFailedEvent,
]


ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]


class ASGI2Protocol(Protocol):
def __init__(self, scope: Scope) -> None:
...

async def __call__(
self, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
...


ASGI2Application = Type[ASGI2Protocol]
ASGI3Application = Callable[
[Scope, ASGIReceiveCallable, ASGISendCallable],
Awaitable[None],
]
ASGIApplication = Union[ASGI2Application, ASGI3Application]
41 changes: 32 additions & 9 deletions uvicorn/middleware/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@
import concurrent.futures
import io
import sys
from typing import Awaitable, Dict, Iterable, Optional, Tuple

from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGISendCallable,
ASGISendEvent,
HTTPScope,
)

def build_environ(scope, message, body):

def build_environ(scope: HTTPScope, message: ASGISendEvent, body: bytes) -> Dict:
"""
Builds a scope and request message into a WSGI environ object.
"""
Expand Down Expand Up @@ -54,18 +63,25 @@ def build_environ(scope, message, body):


class WSGIMiddleware:
def __init__(self, app, workers=10):
def __init__(self, app: ASGI3Application, workers: int = 10) -> None:
self.app = app
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)

async def __call__(self, scope, receive, send):
async def __call__(
self, scope: HTTPScope, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
assert scope["type"] == "http"
instance = WSGIResponder(self.app, self.executor, scope)
await instance(receive, send)


class WSGIResponder:
def __init__(self, app, executor, scope):
def __init__(
self,
app: ASGI3Application,
executor: concurrent.futures.ThreadPoolExecutor,
scope: HTTPScope,
) -> Awaitable:
self.app = app
self.executor = executor
self.scope = scope
Expand All @@ -75,9 +91,11 @@ def __init__(self, app, executor, scope):
self.send_queue = []
self.loop = None
self.response_started = False
self.exc_info = None
self.exc_info: Optional[str] = None

async def __call__(self, receive, send):
async def __call__(
self, receive: ASGIReceiveCallable, send: ASGISendCallable
) -> None:
message = await receive()
body = message.get("body", b"")
more_body = message.get("more_body", False)
Expand All @@ -100,7 +118,7 @@ async def __call__(self, receive, send):
if self.exc_info is not None:
raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])

async def sender(self, send):
async def sender(self, send: ASGISendCallable) -> None:
while True:
if self.send_queue:
message = self.send_queue.pop(0)
Expand All @@ -111,7 +129,12 @@ async def sender(self, send):
await self.send_event.wait()
self.send_event.clear()

def start_response(self, status, response_headers, exc_info=None):
def start_response(
self,
status: str,
response_headers: Iterable[Tuple[bytes, bytes]],
exc_info: Optional[str] = None,
) -> None:
self.exc_info = exc_info
if not self.response_started:
self.response_started = True
Expand All @@ -130,7 +153,7 @@ def start_response(self, status, response_headers, exc_info=None):
)
self.loop.call_soon_threadsafe(self.send_event.set)

def wsgi(self, environ, start_response):
def wsgi(self, environ: Dict, start_response: Awaitable[None]) -> None:
for chunk in self.app(environ, start_response):
self.send_queue.append(
{"type": "http.response.body", "body": chunk, "more_body": True}
Expand Down