Flaskrespon响应对象和make_respon()⽅法
合算Flask视图函数返回的不仅仅是字符串,⽽是会对返回值进⾏⼀些列的封装,变成⼀个respon响应对象
def hello():
# status 200,404,301
# content-type http headers
# content-type = text/html
# Respon
return "*******"
如果视图函数单纯返回"****"的字符串的话,flask会⾃动进⾏⼀些封装让他变成浏览器可以读取的格式,也就是content-type =
text/html,状态码为200。
我们可以使⽤Flask提供的make_respon ⽅法来⾃定义⾃⼰的respon对象
def hello():
# status 200,404,301
# content-type http headers
# content-type = text/html
# Respon
headers = {
'content-type':'text/plain'
}
# 使浏览器识别返回内容为字符串⽽不是html愚人节英语怎么说
respon = make_respon("<html></html>",404)
respon.headers = headers
return respon
make_respon()⽅法说明
1.返回内容
from flask import make_respon
@ute('/makerespon/')
def make_respon_function():每日英语学习网站
respon = make_respon('<h2>羞羞哒</h2>')
英语四级作文题目
童话 英文版return respon, 404
2.返回页⾯
from flask import make_respon
@ute('/makerespon/')
def make_respon_function():
temp = render_template('hello.html')
respon = make_respon(temp)
return respon
>>>注意:make_respon 想要返回页⾯,不能直接写做:make_respon('hello.html'),必须⽤render_template('hello.html')形式。
3.返回状态码
>>>⽅式⼀:在make_respon()中传⼊状态码
from flask import make_respon
ute('/makerespon/')
def make_respon_function():
电话会议英文temp = render_template('hello.html')
respon = make_respon(temp, 200)
return respon
英语谚语带翻译
>>>⽅式⼆:直接return状态码
from flask import make_respon
@ute('/makerespon/')
def make_respon_function():
temp = render_template('hello.html')
respon = make_respon(temp)
return respon, 200
官⽅⽂档
make_respon(rv)
Convert the return value from a view function to an instance of .
Parameters
rv –
the return value from the view function. The view function must return a respon. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv:
str (unicode in Python 2) 可以传⼊⼀个字符串对象,它将被编码为UTF-8并被显⽰在body中
A respon object is created with the string encoded to UTF-8 as the body.老友记中英文字幕
bytes (str in Python 2)happynewyear
A respon object is created with the bytes as the body.
dict 也可以传⼊⼀个字典类型的对象,它将被先变成json格式再返回
A dictionary that will be jsonify’d before being returned.
tuple 也可以传⼊⼀个元组,包含两个或者三个元素,分别是body内容,status状态码,headers响应头(字典类型)
Either (body, status, headers), (body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a instance, status overwrites the exiting value and headers are extended.
这⾥的元组的意思是我们可以再函数中直接通过return来返回这三个或者两个对象,⽽不需要使⽤make_respon()⽅法,Flask会⾃动进⾏识别和封装。
例:
def hello():
headers = {
'content-type':'text/plain'
}
# 使浏览器识别返回内容为字符串⽽不是html return "<html></html>",404,headers