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

feat: add support for custom async iterable objects #43

Merged
merged 2 commits into from
Nov 15, 2022
Merged
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
43 changes: 43 additions & 0 deletions examples/custom_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import asyncio

from fastapi import FastAPI, Depends
from sse_starlette import EventSourceResponse, ServerSentEvent
from starlette import status


class Stream:
def __init__(self) -> None:
self._queue = asyncio.Queue[ServerSentEvent]()

def __aiter__(self) -> "Stream":
return self

async def __anext__(self) -> ServerSentEvent:
return await self._queue.get()

async def asend(self, value: ServerSentEvent) -> None:
await self._queue.put(value)


app = FastAPI()

_stream = Stream()
app.dependency_overrides[Stream] = lambda: _stream


@app.get("/sse")
async def sse(stream: Stream = Depends()) -> EventSourceResponse:
return EventSourceResponse(stream)


@app.post("/message", status_code=status.HTTP_201_CREATED)
async def send_message(message: str, stream: Stream = Depends()) -> None:
await stream.asend(
ServerSentEvent(data=message)
)


if __name__ == "__main__":
import uvicorn

uvicorn.run(app, host="127.0.0.1", port=8000)
3 changes: 1 addition & 2 deletions sse_starlette/sse.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import enum
import inspect
import io
import logging
import re
Expand Down Expand Up @@ -152,7 +151,7 @@ def __init__(
) -> None:
self.sep = sep
self.ping_message_factory = ping_message_factory
if inspect.isasyncgen(content):
if isinstance(content, AsyncIterable):
self.body_iterator = (
content
) # type: AsyncIterable[Union[Any,dict,ServerSentEvent]]
Expand Down
12 changes: 12 additions & 0 deletions tests/integration_testing.http
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,15 @@ GET http://localhost:8000/endless
Accept: application/json

###

# curl -X 'POST'
# 'http://127.0.0.1:8000/message?message=xxx'
# -H 'accept: application/json'
# -d ''
POST http://127.0.0.1:8000/message?message=xxx
accept: application/json
Content-Type: application/x-www-form-urlencoded

###