1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
|
.. _cheatsheet:
Cheatsheet
==========
Basic App
---------
.. code-block:: python
from quart import Quart
app = Quart(__name__)
@app.route("/hello")
async def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run(debug=True)
Routing
-------
.. code-block:: python
@app.route("/hello/<string:name>") # example.com/hello/quart
async def hello(name):
return f"Hello, {name}!"
Request Methods
---------------
.. code-block:: python
@app.route("/get") # GET Only by default
@app.route("/get", methods=["GET", "POST"]) # GET and POST
@app.route("/get", methods=["DELETE"]) # Just DELETE
JSON Responses
--------------
.. code-block:: python
@app.route("/hello")
async def hello():
return {"Hello": "World!"}
Template Rendering
------------------
.. code-block:: python
from quart import render_template
@app.route("/hello")
async def hello():
return await render_template("index.html") # Required to be in templates/
Configuration
-------------
.. code-block:: python
import json
import tomllib
app.config["VALUE"] = "something"
app.config.from_file("filename.toml", tomllib.load)
app.config.from_file("filename.json", json.load)
Request
-------
.. code-block:: python
from quart import request
@app.route("/hello")
async def hello():
request.method
request.url
request.headers["X-Bob"]
request.args.get("a") # Query string e.g. example.com/hello?a=2
await request.get_data() # Full raw body
(await request.form)["name"]
(await request.get_json())["key"]
request.cookies.get("name")
WebSocket
---------
.. code-block:: python
from quart import websocket
@app.websocket("/ws")
async def ws():
websocket.headers
while True:
try:
data = await websocket.receive()
await websocket.send(f"Echo {data}")
except asyncio.CancelledError:
# Handle disconnect
raise
Cookies
-------
.. code-block:: python
from quart import make_response
@app.route("/hello")
async def hello():
response = await make_response("Hello")
response.set_cookie("name", "value")
return response
Abort
-----
.. code-block:: python
from quart import abort
@app.route("/hello")
async def hello():
abort(409)
HTTP/2 & HTTP/3 Server Push
---------------------------
.. code-block:: python
from quart import make_push_promise, url_for
@app.route("/hello")
async def hello():
await make_push_promise(url_for('static', filename='css/minimal.css'))
...
|