跳转至

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

函数的返回值,除了以往直接返回字符串、JSON 外,可使用DFF.RESP(...)进行细节控制。

参数 类型 必须/默认值 说明
data str/dict/list 必须 指定返回的数据
status_code int 200 指定响应状态码
content_type str None 指定响应体类型,如json, text, html
headers dict None 指定 HTTP 响应头(此处不需要重复填写Content-Type
allow_304 bool False 指定为True时,允许浏览器 304 缓存
download str False 指定下载文件名,并将数据作为文件下载
指定本参数后,content_type参数不再起效

如果开启 allow_304,允许浏览器 304 缓存,可以实现接口性能提升。但也可能会因为缓存导致客户端无法及时从接口获取最新内容

指定 download 参数后,系统会自动根据文件扩展名填充 Content-Type,而 content_type 参数会被忽略

常见用例如下:

Python
 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
@DFF.API('用例 1')
def case_1():
    '''
    返回一个由函数内生成的 HTML 页面
    '''
    data = '''<h1>Hello, World!</h1>'''
    return DFF.RESP(data, content_type='html')

@DFF.API('用例 2')
def case_2():
    '''
    返回由函数生成的 JSON 数据
    与 return {"hello": "world"} 等价
    '''
    data = '''{"hello": "world"}'''
    return DFF.RESP(data, content_type='json')

@DFF.API('用例 3')
def case_3():
    '''
    下载由函数生成的文件,并命名为`文章.txt`
    '''
    data = '''Some text'''
    return DFF.RESP(data, download='文章.txt')

@DFF.API('用例 4')
def case_4():
    '''
    指定额外的响应头
    '''
    data = '''<h1>Hello, World!</h1>'''
    headers = {
        'X-Author': 'Tom',
    }
    return DFF.RESP(data, content_type='html', headers=headers)

@DFF.API('用例 5')
def case_5():
    '''
    指定相应代码
    '''
    data = '''<h1>No such data</h1>'''
    return DFF.RESP(data, content_type='html', status_code=404)