...
 
Commits (3)
    https://gitcode.net/WyhPro/wyh_web_tools/-/commit/e0ceffdec4dce07b41f3990ea4ffa5aad230a097 重定向 2021-08-15T14:06:45+08:00 汪云辉 15655267350@163.com https://gitcode.net/WyhPro/wyh_web_tools/-/commit/20c4ad21c2c58c303324d841e5fb35cd133ce78f # 4)返回json视图 2021-08-15T14:08:37+08:00 汪云辉 15655267350@163.com https://gitcode.net/WyhPro/wyh_web_tools/-/commit/e46cdb8ae507184b1e8e97ae26d69c0014737e43 自定义状态码和响应头 2021-08-15T14:12:16+08:00 汪云辉 15655267350@163.com # 5.1) 元祖方式
from flask import url_for, render_template, make_response
from flask import url_for, render_template, make_response, redirect, jsonify
from flask import request
from user import user_blu
......@@ -36,8 +36,8 @@ def upload_file():
#####################################如何在不同的场景里返回不同的响应信息##########################################
# 1)自定义响应对象
@user_blu.route('/demo2')
def demo2():
@user_blu.route('/demo0002')
def demo0002():
# 视图函数可以返回str/bytes, 并且都会最终包装为Response响应对象
# 手动创建响应对象 主要目的为设置响应头
......@@ -55,3 +55,47 @@ def index001():
mstr = 'Hello 黑马程序员'
mint = 10
return render_template('index.html', my_str=mstr, my_int=mint)
# 3)重定向
@user_blu.route('/demo002')
def demo002():
# 如果想要获取视图函数的动态url,必须手动设置路由变量的值(可以传参)
url = url_for("demo003", user_id=11)
return redirect('http://www.itheima.com')
# url发生变化,也不需要改代码,有利于url的重构
# return redirect(url_for(index)) # 配合url_for使用,index为endpoint
@user_blu.route('/demo003/<user_id>')
def demo003(user_id):
print(user_id)
return "hello"
# 4)返回json
@user_blu.route('/demo3')
def demo3():
json_dict = {
"user_id": 10,
"user_name": "laowang"
}
# json_str= json.dumps(json_dict ) # 没有指定content-type
# return json_str
# 可以将字典转为json字符串,并且自动设置content-type为application/json
return jsonify(json_dict)
# return jsonify(user_id=10, user_name="laowang") # 也支持关键字实参形式
# 5)自定义状态码和响应头
# 5.1) 元祖方式
# 可以返回一个元组,这样的元组必须是 (response, status, headers) 的形式,且至少包含一个元素。 status 值会覆盖状态代码, headers 可以是一个列表或字典,作为额外的消息标头值。
@user_blu.route('/demo4')
def demo4():
# 目的是为了和前端进行交互,定义一套自定义的交互规则
# return '状态码为 666', 666
# return '状态码为 666', 666, [('Itcast', 'Python')]
return '状态码为 666', 666, {'Itcast': 'Python'}