跳轉到

指令碼開發 / 響應資料 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 能否序列化。序列化失敗,或同時使用 download 與 data=None,都會使 Func 響應失敗。

必須直接返回 DFF.RESP(...) 建立的響應物件;將它嵌入其他字典或列表不會應用狀態碼、Header 或內容型別。

Warning

allow_304=True 可能讓客戶端取得快取內容,資料頻繁變化時不應開啟。自定義響應 Header 中不得包含金鑰或其他敏感資訊。