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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| from flask import Blueprint, redirect, url_for, make_response, request, render_template, session
# 模块化管理路由 # 第一步:生成蓝图对象 from utils.functions import login_required
blueprint = Blueprint('first', __name__)
@blueprint.route('/') def hello(): return 'hello world!'
@blueprint.route('/stu/<id>/') def stu(id): return 'hello stu:%s' % id
# 1.定义路由跳转到hello方法 # 2.定义路由跳转到stu方法
@blueprint.route('/redirect') def my_redirect(): # redirect: 跳转 # url_for: 反向解析 # ‘first.hello’: 蓝图的第一个参数,跳转到的函数名 return redirect(url_for('first.hello'))
@blueprint.route('/redirect_id/') def stu_redirect(): return redirect(url_for('first.stu', id=3))
@blueprint.route('/make_response/') def my_response(): # make_response: 创建响应 # 第一个参数:响应内容 # 第二个参数:响应状态码 res = make_response('<h2>还行吧</h2>', 200) # 设置cookie,max_age以秒为单位,expires以datetime为单位 res.set_cookie('token', '123456', max_age=6000) return res
@blueprint.route('/del_cookie/') def del_cookie(): res = make_response('<h2>删除cookie</h2>', 200) res.delete_cookie('token') return res
@blueprint.route('/req/', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) def req(): if request.method == 'GET': # 获取GET请求中传递的参数:request.args # 获取GET请求中全部name参数,request.args.getlist('name') # 获取GET请求中第一个name参数,request.args.get('name')/request.args['name'] return 'hello'
if request.method == 'POST': # 获取POST请求中传递的参数:request.form # 获取POST请求中全部name参数,request.form.getlist('name') # 获取POST请求中第一个name参数,request.args.get('name')/request.args['name']
return 'hello post!'
@blueprint.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html')
if request.method == 'POST': # 模拟登陆 username = request.form.get('username') password = request.form.get('password') if username == 'coco' and password == '123456': session['user_id'] = 1 return redirect(url_for('first.index'))
# 登录校验装饰器
@blueprint.route('/index/') @login_required def index(): return render_template('index.html')
|