跳转至

脚本开发 / 响应数据 DFF.RESP

普通 JSON 或文本响应可以直接 return。需要控制 HTTP 状态码、Header、下载文件名或内容类型时,使用 DFF.RESP(...)

磁盘文件应使用 DFF.RESP_FILE(...),MB 级数据应使用 DFF.RESP_LARGE_DATA(...)

参数

参数 类型 必须 / 默认值 说明
data 任意 JSON 可序列化值 必须 响应体
status_code int 200 HTTP 状态码
content_type str None 响应体类型,如 "json""text""html"
headers dict None 额外响应头,无需包含 Content-Type
allow_304 bool False 是否允许浏览器使用 304 缓存
download bool / str False True 生成默认文件名,字符串指定文件名;启用后 content_type 不再生效
示例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def html_response():
    return DFF.RESP('<h1>Hello</h1>', content_type='html')

def json_response():
    return DFF.RESP('{"hello": "world"}', content_type='json')

def download_response():
    return DFF.RESP('Some text', download='article.txt')

def header_response():
    return DFF.RESP('ok', headers={'X-Author': 'Tom'})

def not_found_response():
    return DFF.RESP({'error': 'not found'}, status_code=404)

构造响应时会验证 data 能否序列化。序列化失败,或同时使用 downloaddata=None,都会使 Func 响应失败。

必须直接返回 DFF.RESP(...) 创建的响应对象;将它嵌入其他字典或列表不会应用状态码、Header 或内容类型。

Warning

allow_304=True 可能让客户端取得缓存内容,数据频繁变化时不应开启。自定义响应 Header 中不得包含密钥或其他敏感信息。