CBV、正则

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()
原文地址:https://www.cnblogs.com/ShenJunHui6/p/11219479.html