Debian Codegraph @

docs_src/stream_data/tutorial001_py310.py

raw
1 from collections.abc import AsyncIterable, Iterable
2
3 from fastapi import FastAPI
4 from fastapi.responses import StreamingResponse
5
6 app = FastAPI()
7
8
9 message = """
10 Rick: (stumbles in drunkenly, and turns on the lights) Morty! You gotta come on. You got--... you gotta come with me.
11 Morty: (rubs his eyes) What, Rick? What's going on?
12 Rick: I got a surprise for you, Morty.
13 Morty: It's the middle of the night. What are you talking about?
14 Rick: (spills alcohol on Morty's bed) Come on, I got a surprise for you. (drags Morty by the ankle) Come on, hurry up. (pulls Morty out of his bed and into the hall)
15 Morty: Ow! Ow! You're tugging me too hard!
16 Rick: We gotta go, gotta get outta here, come on. Got a surprise for you Morty.
17 """
18
19
20 @app.get("/story/stream", response_class=StreamingResponse)
21 async def stream_story() -> AsyncIterable[str]:
22 for line in message.splitlines():
23 yield line
24
25
26 @app.get("/story/stream-no-async", response_class=StreamingResponse)
27 def stream_story_no_async() -> Iterable[str]:
28 for line in message.splitlines():
29 yield line
30
31
32 @app.get("/story/stream-no-annotation", response_class=StreamingResponse)
33 async def stream_story_no_annotation():
34 for line in message.splitlines():
35 yield line
36
37
38 @app.get("/story/stream-no-async-no-annotation", response_class=StreamingResponse)
39 def stream_story_no_async_no_annotation():
40 for line in message.splitlines():
41 yield line
42
43
44 @app.get("/story/stream-bytes", response_class=StreamingResponse)
45 async def stream_story_bytes() -> AsyncIterable[bytes]:
46 for line in message.splitlines():
47 yield line.encode("utf-8")
48
49
50 @app.get("/story/stream-no-async-bytes", response_class=StreamingResponse)
51 def stream_story_no_async_bytes() -> Iterable[bytes]:
52 for line in message.splitlines():
53 yield line.encode("utf-8")
54
55
56 @app.get("/story/stream-no-annotation-bytes", response_class=StreamingResponse)
57 async def stream_story_no_annotation_bytes():
58 for line in message.splitlines():
59 yield line.encode("utf-8")
60
61
62 @app.get("/story/stream-no-async-no-annotation-bytes", response_class=StreamingResponse)
63 def stream_story_no_async_no_annotation_bytes():
64 for line in message.splitlines():
65 yield line.encode("utf-8")