视图函数返回一个字符串、字典、元组或者什么都不返回,Flask 分别怎么处理?这篇把常见返回值和非法返回值都跑一遍。
返回值 状态 Content-Type 正文
str 200 OK text/html; charset=utf-8 hello
bytes 200 OK text/html; charset=utf-8 raw bytes
dict 200 OK application/json {"a":1,"b":[1,2]}\n
list 200 OK application/json [1,2,{"k":"v"}]\n
(body, 201) 201 CREATED text/html; charset=utf-8 created
(body, headers) 200 OK text/html; charset=utf-8 h
(body, 202, headers) 202 ACCEPTED text/html; charset=utf-8 both
(body, "404 自定义") 404 自定义短语 text/html; charset=utf-8 nf
generator 200 OK text/html; charset=utf-8 abc
Response 200 OK text/plain; charset=utf-8 resp
dict + status 201 CREATED application/json {"ok":true}\n
dataclass 500 INTERNAL SERVER ERROR text/html; charset=utf-8 <!doctype html>\n<html lang=en>\n<title>500
None 500 INTERNAL SERVER ERROR text/html; charset=utf-8 <!doctype html>\n<html lang=en>\n<title>500
int 500 INTERNAL SERVER ERROR text/html; charset=utf-8 <!doctype html>\n<html lang=en>\n<title>500
tuple 长度 4 500 INTERNAL SERVER ERROR text/html; charset=utf-8 <!doctype html>\n<html lang=en>\n<title>500
set 500 INTERNAL SERVER ERROR text/html; charset=utf-8 <!doctype html>\n<html lang=en>\n<title>500 上一篇:abort() 如何生成错误响应;下一篇:WSGI Callable 的真实结构。
None: TypeError: The view function for None did not return a valid response. The function either returned None or ended without a return statement. int: TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a int. tuple 长度 4: TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers). set: TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a set. dataclass: TypeError: The view function did not return a valid response. The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable, but it was a P.
app.make_response(("hi", 201, {"X-A": "1"})) → Response 201 CREATED {'X-A': '1', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '2'}
app.make_response({"k": "v"}) → application/json {"k":"v"}
手动设置 → Set-Cookie: sid=abc; HttpOnly; Path=/ | X-C: 3str Content-Length = 5 | Transfer-Encoding = None generator Content-Length = None | Transfer-Encoding = None
GET / → 200 OK X-Powered-By = lab | 类型 WrapperTestResponse GET /j → 200 OK X-Powered-By = lab | 类型 WrapperTestResponse GET /nope → 404 NOT FOUND X-Powered-By = lab | 类型 WrapperTestResponse