| 1 |
from litestar import Litestar, MediaType, Request, Response, get |
| 2 |
|
| 3 |
|
| 4 |
@get("/resource", sync_to_thread=False) |
| 5 |
def retrieve_resource(request: Request) -> Response[bytes]: |
| 6 |
provided_types = [MediaType.TEXT, MediaType.HTML, "application/xml"] |
| 7 |
preferred_type = request.accept.best_match(provided_types, default=MediaType.TEXT) |
| 8 |
|
| 9 |
content = None |
| 10 |
if preferred_type == MediaType.TEXT: |
| 11 |
content = b"Hello World!" |
| 12 |
elif preferred_type == MediaType.HTML: |
| 13 |
content = b"<h1>Hello World!</h1>" |
| 14 |
elif preferred_type == "application/xml": |
| 15 |
content = b"<xml><msg>Hello World!</msg></xml>" |
| 16 |
return Response(content=content, media_type=preferred_type) |
| 17 |
|
| 18 |
|
| 19 |
app = Litestar(route_handlers=[retrieve_resource]) |
| 20 |
|
| 21 |
# run: /resource |
| 22 |
# run: /resource -H "Accept: text/html" |
| 23 |
# run: /resource -H "Accept: application/xml" |