zoukankan      html  css  js  c++  java
  • flask之路由route

      1 '''
      2 app.py中的源码def route(self, rule, **options)
      3 @app.route()路由参数使用:
      4     1.第一个位置参数为路由分发的请求路径
      5         ①静态参数路由:/index  /   /base 等
      6         ②动态参数路由:/index/<name> 在路由中使用了<变量名>的路由称为动态路由,
      7                     动态路由参数<name>会接收字符串和数字类型,但在制定了int时会优先调用该视图
      8                     可以指定int型,如/index/<int:id>,在视图函数中必须有同名的形参来接收
      9 
     10     2.methods=['GET','PosT']
     11         2.1当前视图函数支持的请求方式(405当前请求方式不被允许),
     12         2.2参数为可迭代对象,请求方式不区分大小写,不设置默认为GET
     13 
     14 
     15     3.endpoint=''
     16          3.1路由映射视图函数,endpoint不指定默认为视图函数名(view_func.__name__)
     17          3.2项目中存储视图函数的view_funcs是以{endpoint:view_func}形式存储,因此视图函数不能同名,
     18          3.3在使用自定义装饰器时注意指定唯一的endpoint,以避免在多个视图函数使用自定义装饰器时报错;
     19 
     20 
     21     4.defaults={key:value}
     22         默认参数设置,必须在视图函数中定义一个形参来接收
     23 
     24     5.redirect_to=''
     25         永久重定向(301或者308)
     26         应用场景:用户之前收藏的是视图函数对应的路由地址,后来页面不在使用,换了新的路径,为了避免用户收藏的不能访问,因此设置永久重定向
     27 
     28     6.strict_slashes=True/False
     29         设置路由路径匹配是否为严格模式,默认不设置为严格路由匹配模式
     30 
     31     7.补充小知识:
     32         falsk中通过视图函数名反向解析请求路径:
     33             ①from  flask import url_for
     34             ②url_for('函数名')==>当前视图函数对应的路由请求路径(具体见知识点6)
     35 FBV:app.add_url_rule('/',endpoint='',view_func=func)     CBV:app.sdd_url_rule('/',endpoint='',view_func=CLASS.as_view(name=''))
     36 '''
     37 from flask import Flask, render_template, request, session, redirect, url_for
     38 
     39 app = Flask(__name__)
     40 app.config['DEBUG'] = True
     41 app.secret_key = 'werf23456'
     42 
     43 
     44 # 1.flaskl路由:
     45 # 1.1静动态路由
     46 @app.route('/index')
     47 def index():
     48     return f'静态路由请求!'
     49 
     50 
     51 # 1.2动态参数路由
     52 # 1.2.1动态路由匹配变量
     53 @app.route('/index/<name>')  # http://192.168.16.14:9000/index/yang
     54 def index2(name):
     55     return f'当前请求的动态参数为:{name}'  # 当前请求的动态参数为:yang
     56 
     57 
     58 # 1.2.2动态路由变量指定匹配
     59 @app.route('/index/name=<name>')  # http://192.168.16.14:9000/index/name=yang
     60 def index3(name):
     61     return f'当前请求的动态参数为:{name}'  # 当前请求的动态参数name为:yang
     62 
     63 
     64 # 1.2.3动态路由整数变量匹配
     65 @app.route('/index/<int:id>')  # http://192.168.16.14:9000/index/1234
     66 def index4(id):
     67     return f'当前请求的页码为:{id}'  # 当前请求页码为:1234
     68 
     69 
     70 # 2.methods=[]支持的请求方式参数设置,不设置默认为GET
     71 @app.route('/login', methods=['GET', 'PoSt'])  # 请求参数设置不区分大小写,源码中自动进行了upper
     72 def login():
     73     if request.method == 'GET':
     74         return render_template('login.html')
     75     elif request.method == 'POST':
     76         username = request.form.get('username')
     77         pwd = request.form.get('pwd')
     78         if username == 'yang' and pwd == '123456':
     79             session['username'] = username
     80             return 'login successed 200  ok!'
     81         else:
     82             return 'login failed!!!'
     83 
     84 
     85 # 3.endpoint=''路由映射视图函数
     86 '''
     87 自定义装饰器装饰多个视图函数时,如果在路由中没有指定唯一的endpoint,
     88 则所有装饰的视图函数返回的都是装饰器中的inner函数,同名因此会报错
     89 AssertionError: View function mapping is overwriting an existing endpoint function: inner
     90 '''
     91 
     92 
     93 def auth(func):
     94     def inner(*args, **kwargs):
     95         if session.get('username'):
     96             return func()
     97         else:
     98             return '未登录无权访问!'
     99 
    100     return inner
    101 
    102 
    103 @app.route('/data1', endpoint='data1')
    104 @auth
    105 def data1():
    106     return '您已登录成功,通过路径/data1来到当前页面!'
    107 
    108 
    109 @app.route('/data2', endpoint='data2')
    110 @auth
    111 def data2():
    112     return '您已登录成功,通过路径/data2来到当前页面!'
    113 
    114 
    115 # 4.defaults={key:value}默认参数
    116 @app.route('/key', defaults={'id': 23})
    117 def key(id):
    118     return f'路由设置的默认参数值为:{id}'
    119 
    120 
    121 # 5.redirect_to=''永久重定向(301或者308状态码)
    122 @app.route('/admin', redirect_to='/redirect')
    123 def admin():
    124     return '原页面'
    125 
    126 
    127 @app.route('/redirect')
    128 def redi():
    129     return '访问/admin永久重定向的新页面!'
    130 
    131 
    132 # 6.strict_slashes=True/False  设置路由路径匹配是否为严格模式,默认不设置为严格路由匹配模式
    133 #(对于在请求路径加了/的路径,在进行路由严格模式匹配时,如果在请求时未加/,flask会进行返回308加上/重定向)
    134 
    135 #6.1不设置strict_slashes默认未严格模式,在路由后边没有/s时,如果访问加上就会报错404
    136 @app.route('/strict_true', strict_slashes=True)
    137 def strict_true():
    138     return f'严格模式匹配{url_for("strict_true")}'
    139 
    140 #6.2指定strict_slashes=False非严格模式时,,在路由后边加/依然可以正常映射
    141 @app.route('/strict_false/', strict_slashes=False)
    142 def strict_false():
    143     return f'非严格模式路由匹配{url_for("strict_false")}'
    144 
    145 
    146 
    147 if __name__ == '__main__':
    148     app.run('0.0.0.0', 9000)
  • 相关阅读:
    WEBAPP开发技巧
    手机中的javascript事件
    I6下实现FIXED
    vim 使用帮助
    javascript小技巧
    webkitbox & translate CSS3动画详解
    backbone中的实例中文注释
    getClientRect和getBoundingClientRect获取节点的屏幕距离
    javascript判定不同浏览器
    jQuery中的trigger(type, [data]) 原生实现方法
  • 原文地址:https://www.cnblogs.com/open-yang/p/11172301.html
Copyright © 2011-2022 走看看