Flask 第四话之视图高级类用法

1、add_url_rule(rule, endpoint=None, view_func=None)

注:这个方法用来添加url与视图函数的映射,如果没有填写`endpoint`,默认使用`view_func`的名字作为`endpoint`。

app.add_url_rule('/list/',view_func=list,endpoint='list')

2、@app.route(rule,**options):底层依然是使用add_url_rule这个函数实现路由映射的

@app.route('/')
def index():
    return render_template('index.html')

一、标准类视图函数

实例1、URL返回JSON数据

from flask import views,jsonify

class JsonView(views.View):
    def get_data(self):
        raise NotImplementedError

    def dispatch_request(self):
        return jsonify(self.get_data())

class ListViews(JsonView):
    def get_data(self):
        return {'a':'111','b':'222'}

# 第一步:匹配url,找到ListViews方法
# 第二步:执行dispatch_request方法,找到父类JsonView =》dispatch_request()
# 第三步:return jsonify(self.get_data()) ===》找到自己的get_data()方法 ===》转换json格式并返回数据
app.add_url_rule('/list/',endpoint='list',view_func=ListViews.as_view(
    'list'
))

实例2、多个URL获取相同数据

from flask import views,render_template

class GuangGaoViews(views.View):
    def __init__(self):
        super(GuangGaoViews,self).__init__()
        self.context = {
            'a':'广告数据'
        }

class LoginViews(GuangGaoViews):
    def dispatch_request(self):
        return render_template('login.html',**self.context)

class RegistViews(GuangGaoViews):
    def dispatch_request(self):
        return render_template('regist.html',**self.context)

app.add_url_rule('/login/',view_func=LoginViews.as_view('login'))
app.add_url_rule('/regist/',view_func=RegistViews.as_view('regist'))

猜你喜欢

转载自www.cnblogs.com/lee-xingxing/p/12358468.html