腳本開發 / 響應數據 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():
'''
下載由函數生成的文件,並命名為`article.txt`
'''
data = '''Some text'''
return DFF.RESP(data, download='article.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)
|