Skip to content

响应

Starlette 包含一些响应类,用于在 send 通道上发送适当的 ASGI 消息。

响应

签名: Response(content, status_code=200, headers=None, media_type=None)

  • content - 一个字符串或字节串。
  • status_code - 一个整数型的 HTTP 状态码。
  • headers - 字符串字典。
  • media_type - 一个给出媒体类型的字符串。例如:"text/html"

Starlette 将自动包含一个 Content-Length 标头。它还将根据 media_type 包含一个 Content-Type 标头,并为文本类型附加一个字符集,除非在 media_type 中已经指定了字符集。

一旦您实例化了一个响应,您可以通过将其作为 ASGI 应用程序实例进行调用来发送它。

from starlette.responses import Response


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = Response('Hello, world!', media_type='text/plain')
    await response(scope, receive, send)

Starlette 提供了一个 set_cookie 方法,允许您在响应对象上设置 Cookie 。

签名: Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax")

  • key - 一个将作为 Cookie 键的字符串。
  • value - 一个将作为 Cookie 值的字符串。
  • max_age - 一个以秒为单位定义 Cookie 生存期的整数。一个负整数或值为 0 将立即丢弃 Cookie。 Optional
  • expires - 要么是一个整数,用于定义 Cookie 到期前的秒数,要么是一个日期时间。 Optional
  • path - 一个指定该 Cookie 将应用于的路由子集的字符串。 Optional
  • domain - 一个指定 cookie 有效的域的字符串。 Optional
  • secure - 一个布尔值,表示只有在使用 SSL 和 HTTPS 协议发出请求时,Cookie 才会被发送到服务器。 Optional
  • httponly - 一个布尔值,表示通过 Document.cookie 属性、 XMLHttpRequestRequest API,无法通过 JavaScript 访问该 Cookie。 Optional
  • samesite - 一个指定 cookie 的 sameSite 策略的字符串。有效值为 'lax''strict''none' 。默认为 'lax'Optional

相反,Starlette 还提供了一个 delete_cookie 方法来手动使设置的 Cookie 过期。

签名: Response.delete_cookie(key, path='/', domain=None)

HTML 响应

接收一些文本或字节并返回一个 HTML 响应。

from starlette.responses import HTMLResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = HTMLResponse('<html><body><h1>Hello, world!</h1></body></html>')
    await response(scope, receive, send)

纯文本响应

接收一些文本或字节并返回一个纯文本响应。

from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

JSON 响应

获取一些数据并返回一个 application/json 编码的响应。

from starlette.responses import JSONResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = JSONResponse({'hello': 'world'})
    await response(scope, receive, send)

自定义 JSON 序列化

如果您需要对 JSON 序列化进行细粒度控制,可以子类化 JSONResponse 并覆盖 render 方法。

例如,如果您想要使用第三方 JSON 库,例如 orjson:

from typing import Any

import orjson
from starlette.responses import JSONResponse


class OrjsonResponse(JSONResponse):
    def render(self, content: Any) -> bytes:
        return orjson.dumps(content)

一般来说,除非您要对特定端点进行微优化或需要序列化非标准对象类型,否则默认情况下您可能希望坚持使用 JSONResponse

重定向响应

返回一个 HTTP 重定向。默认使用 307 状态码。

from starlette.responses import PlainTextResponse, RedirectResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    if scope['path'] != '/':
        response = RedirectResponse(url='/')
    else:
        response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

流式响应

接受一个异步生成器或一个普通的生成器/迭代器,并对响应体进行流处理。

from starlette.responses import StreamingResponse
import asyncio


async def slow_numbers(minimum, maximum):
    yield '<html><body><ul>'
    for number in range(minimum, maximum + 1):
        yield '<li>%d</li>' % number
        await asyncio.sleep(0.5)
    yield '</ul></body></html>'


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    generator = slow_numbers(1, 10)
    response = StreamingResponse(generator, media_type='text/html')
    await response(scope, receive, send)

请注意,类文件对象(如由 open() 创建的那些对象)是普通的迭代器。因此,您可以在 StreamingResponse 中直接返回它们。

文件响应

以异步方式将文件作为响应进行流式传输。

与其他响应类型相比,实例化时需要一组不同的参数:

  • path - 要进行流式传输的文件的文件路径。
  • headers - 作为字典的任何要包含的自定义标头。
  • media_type - 一个给出媒体类型的字符串。如果未设置,将使用文件名或路径来推断媒体类型。
  • filename - 若设置,其将包含在响应 Content-Disposition 中。
  • content_disposition_type - 将包含在响应 Content-Disposition 中。可设置为“附件”(默认值)或“内联”。

文件响应将包含适当的 Content-LengthLast-ModifiedETag 标头。

from starlette.responses import FileResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = FileResponse('statics/favicon.ico')
    await response(scope, receive, send)

第三方回应

事件源响应

一个实现服务器发送事件的响应类。它能够实现从服务器到客户端的事件流,而无需 WebSockets 的复杂性。

baize.asgi.FileResponse

作为 Starlette FileResponse 的顺利替代品,它将自动处理 Head 方法和 Range 请求。