flask框架 视图函数当中 各种实用情况简单配置
1 建立连接
2 路由参数
3 返回网络状态码
4 自定义错误页面
5 重定向
6 正则url限制 和 url 优化
7 设置和获取cookie
1 #coding:utf8 2 # 导入flask 3 from flask import Flask,abort,redirect,make_response,request 4 from werkzeug.routing import BaseConverter 5 6 7 # Flask 接受一个参数__name__ 作用是指明应用的位置 8 app = Flask(__name__) 9 10 11 12 ''' 13 1 建立一个前后台链接 14 装饰器的作用是陆游映射到视图函数index 15 访问根目录就会进入index视图函数 16 ''' 17 @app.route('/') 18 def index(): 19 # 返回后会调用make_response 20 return "你好 世界!" 21 22 23 ''' 24 2 给路由传参数 25 传递的参数在<name>当中 这个变量名称也要传递给视图函数 26 可以在<int:name> 或者<string:name> 指定传递参数的类型 27 不指定类型默认使用string类型 28 ''' 29 @app.route('/attr/<string:attr>') 30 def attr(attr): 31 return "hello,%s"%attr 32 33 34 ''' 35 3 返回网络状态码的两种方式 36 01 return 字符串,状态码 37 02 abort(状态码) 38 200 成功 39 300 重定向 40 404 未找到 41 500 服务器内部错误 42 ''' 43 #01 return 字符串,状态码 这种方式 可以返回不存在的状态码 前端依然能得到页面 44 @app.route('/status') 45 def status(): 46 # 用这种方式可以返回假的状态码 前端依然能够渲染 47 return 'hello status',999 48 49 #02 利用abort(状态码) 进行返回状态码,只能写入真的状态码 50 # 这个函数的作用是 自定义我们项目的 出错页面 51 @app.route('/abort') 52 def geive500(): 53 abort(500) 54 55 ''' 56 4 捕获访问我们flask后台发生各种错误的情况 57 利用@app.errorhandler(500) 进行装饰 能截获500的response 58 ''' 59 # 捕获500异常 函数当中接受到错误信息 60 @app.errorhandler(500) 61 def error500(e): 62 return "您请求的页面后台发生错误!错误信息:%s"%e 63 @app.errorhandler(404) 64 def error404(e): 65 return "您访问的页面飞去了火星!信息:%s"%e 66 67 ''' 68 5 重定向 69 有两种方式: 70 01 redirect(url) 71 02 url_for(视图函数) 72 ''' 73 @app.route('/redirect') 74 def redir(): 75 return redirect('http://www.baidu.com') 76 77 78 ''' 79 6 url正则 80 两个用途: 限制访问 和 优化访问路径 81 使用: 82 01首先要 定义一个继承自BaseConverter的子类 83 在子类里面调用父类的初始化方法 84 重写父类的变量 85 02然后 给applurl_map.converters 字典添加re健 和 我们自己写的类做val 86 87 03最后 视图函数的app.route('路径<re(正则),变量名>') 88 变量名要传给视图函数做参数 89 ''' 90 # 01 写一个继承自 BaseConverter的子类 相应的方法和属性要重写 91 class Regex_url(BaseConverter): 92 def __init__(self,url_map,*args): 93 super(Regex_url,self).__init__(url_map) 94 self.regex = args[0] 95 # 02 添加re映射 96 app.url_map.converters['re'] = Regex_url 97 # 03 正则匹配参数 98 # 利用正则对传入参数进行限制 99 # 只有1到3位小写英文才能成功 否则都是404 100 @app.route('/attr2/<re("[a-z]{1,3}"):attr>') 101 def attr2(attr): 102 return "hello %s"%attr 103 104 105 ''' 106 7 设置cookie 和 获取 cookie 107 设置cookie: 108 利用 make_response() 拿到response对象 109 response.set_cookie(key,val) 110 获取cookie: 111 利用request.cookies.get(key) 获取cookie 112 ''' 113 # 设置cookie 114 @app.route('/set_cookie') 115 def setCookie(): 116 response = make_response('设置cookie') 117 response.set_cookie('log','设置的cookie') 118 return response 119 120 # 获取cookie 121 @app.route('/get_cookie') 122 def getCookie(): 123 log = request.cookies.get('log') 124 return log 125 126 127 if __name__ == '__main__': 128 # 执行后台服务器 129 app.run(debug=True)
来源:https://www.cnblogs.com/Lin-Yi/p/7739713.html