Debian Codegraph @

docs/reference/response_values.rst

raw
1 .. _response_values:
2
3 Response Return Values
4 ======================
5
6 Response functions can return a number of different types as the
7 response value which will trigger different responses to the
8 client. The possible direct returns are,
9
10 Response Values
11 ---------------
12
13 str
14 ^^^
15
16 .. code-block:: python
17
18 return "Hello"
19 return await render_template("index.html")
20
21 A solitary string return indicates that you intend to return a string
22 mimetype ``text/html``. The string will be encoded using the default
23 :attr:`~quart.wrappers._BaseRequestResponse.charset`.
24
25 dict
26 ^^^^
27
28 .. code-block:: python
29
30 return {"a": "b"}
31
32 A solitary dict return indicates that you intend to return json,
33 ``application/json``. The jsonify function will be used to encode the
34 dictionary.
35
36 list
37 ^^^^
38
39 .. code-block:: python
40
41 return ["a", "b"]
42
43 A solitary list return indicates that you intend to return json,
44 ``application/json``. The jsonify function will be used to encode the
45 list.
46
47 Response
48 ^^^^^^^^
49
50 .. code-block:: python
51
52 @app.route('/')
53 async def route_func():
54 return Response("Hello")
55
56 Returning a Response instance indicates that you know exactly what you
57 wish to return.
58
59 AsyncGenerator[bytes, None]
60 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
61
62 .. code-block:: python
63
64 @app.route('/')
65 async def route_func():
66
67 async def agen():
68 data = await something
69 yield data
70
71 return agen()
72
73 Returning an async generator allows for the response to be streamed to
74 the client, thereby lowing the peak memory usage, if combined with a
75 ``Transfer-Encoding`` header with value ``chunked``.
76
77 Generator[bytes, None, None]
78 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
79
80 .. code-block:: python
81
82 @app.route('/')
83 async def route_func():
84
85 def gen():
86 yield data
87
88 return gen()
89
90 Returning an generator allows for the response to be streamed to the
91 client, thereby lowing the peak memory usage, if combined with a
92 ``Transfer-Encoding`` header with value ``chunked``.
93
94 Combinations
95 ------------
96
97 Any of the above Response Values can be combined, as described,
98
99 Tuple[ResponseValue, int]
100 ^^^^^^^^^^^^^^^^^^^^^^^^^
101
102 .. code-block:: python
103
104 @app.route('/')
105 async def route_func():
106 return "Hello", 200
107
108 A tuple of a Response Value and a integer indicates that you intend to
109 specify the status code.
110
111 Tuple[str, int, Dict[str, str]]
112 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
113
114 .. code-block:: python
115
116 @app.route('/')
117 async def route_func():
118 return "Hello", 200, {'X-Header': 'Value'}
119
120 A tuple of a Response Value, integer and dictionary indicates that you intend
121 to specify additional headers.