File: response_content.py

package info (click to toggle)
litestar 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,568 kB
  • sloc: python: 70,588; makefile: 254; javascript: 104; sh: 60
file content (23 lines) | stat: -rw-r--r-- 831 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from litestar import Litestar, MediaType, Request, Response, get


@get("/resource", sync_to_thread=False)
def retrieve_resource(request: Request) -> Response[bytes]:
    provided_types = [MediaType.TEXT, MediaType.HTML, "application/xml"]
    preferred_type = request.accept.best_match(provided_types, default=MediaType.TEXT)

    content = None
    if preferred_type == MediaType.TEXT:
        content = b"Hello World!"
    elif preferred_type == MediaType.HTML:
        content = b"<h1>Hello World!</h1>"
    elif preferred_type == "application/xml":
        content = b"<xml><msg>Hello World!</msg></xml>"
    return Response(content=content, media_type=preferred_type)


app = Litestar(route_handlers=[retrieve_resource])

# run: /resource
# run: /resource -H "Accept: text/html"
# run: /resource -H "Accept: application/xml"