加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

CBV、正则

发布时间:2020-12-14 05:47:31 所属栏目:百科 来源:网络整理
导读:CBV(源码分析) from flask import Flask,viewsapp = Flask(__name__)class IndexView(views.MethodView): methods = ['GET','POST'] def get(self): return '这个是get请求' def post(self): return '这个是post请求'app.add_url_rule('/',view_func=IndexVi

CBV(源码分析)

from flask import Flask,views

app = Flask(__name__)


class IndexView(views.MethodView):
    methods = ['GET','POST']

    def get(self):
        return '这个是get请求'

    def post(self):
        return '这个是post请求'


app.add_url_rule('/',view_func=IndexView.as_view(name='index'),endpoint='xxx')

if __name__ == '__main__':
    app.run()
app.add_url_rule参数
@app.route和app.add_url_rule参数:
ruel,URL规则
view_func,视图函数名称
defaults = None,默认值,当URL中无参数,函数需要参数时,使用defaults = {'k',:'v'}
为函数提供参数
endpoint = None,名称,用于反向生成URL,即:url_for("名称")
methods = None,允许请求方式,如:["GET","POST"]
# 对URL最后的/符号是否严格要求
strict_slashes = None
'''
        @app.route('/index',strict_slashes=False)
        #访问http://www.xx.com/index/ 或http://www.xx.com/index均可
        @app.route('/index',strict_slashes=True)
        #仅访问http://www.xx.com/index
    '''
redirect_to = None
'''
        @app.route('/index/<int:nid>',redirect_to='/home/<nid>')
    '''
支持正则
'''
1. 写类,继承BaseConverter
2. 注册:app.url_map.converters
3. 使用:@app.route('/index/<regex("d+"):nid>') 正则表达式会当作第二个参数传递到类中
'''
            from flask import Flask,views,url_for
            from werkzeug.routing import BaseConverter
            app = Flask(import_name=__name__)
            class RegexConverter(BaseConverter):
                """
                自定义URL匹配正则表达式
                """
                def __init__(self,map,regex):
                    super(RegexConverter,self).__init__(map)
                    self.regex = regex

                def to_python(self,value):
                    """
                    路由匹配时,匹配成功后传递给视图函数中参数的值
                    """
                    return int(value)

                def to_url(self,value):
                    """
                    使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
                    """
                    val = super(RegexConverter,self).to_url(value)
                    return val
            # 添加到flask中
            # regex 是我们自定义的
            app.url_map.converters['regex'] = RegexConverter


            @app.route('/index/<regex("d+"):nid>')
            def index(nid):
                print(type(nid))
                print(url_for('index',nid='888'))
                return 'Index'

            if __name__ == '__main__':
                app.run()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读