视图扩展点

描述

这个扩展缩写为vep。

视图扩展点是插件直接增加路由函数的简单方式,因为之前的版本中,要增加路由只能通过蓝图。

插件需要通过register函数返回vep字段,返回的vep数据类型可以是字典、列表或元组。

字典的话,格式是{rule:, view_func:},表示增加单个路由,这个数据内容即 add_url_rule() 的参数,参考文档 add_url_rule ,一个常用的示例是:

def vep():
    return "vep"

dict(rule="/vep", view_func=vep, endpoint="vep", methods=["GET", "POST"])

其他类型表示为多个路由,嵌套多个上面那种字典数据即可。

Flask-PluginKit通过 _vep_handler() 加载vep,这个方法会检测vep规则和内容。

vep on blueprint

vep允许设置到蓝图上,格式是:{_blueprint: blueprint-name, rule:/path, view_func:xx}。

要求蓝图真实存在,否则引发 PEPError

在 3.6.0 版本加入.

示例

  • 注册vep

def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

def upload_file():
    if request.method == 'POST':
        # save post file
        return redirect(url_for('uploaded_file', filename=filename))
    else:
        return '''
        <form method=post enctype=multipart/form-data>
            <input type=file name=file>
            <input type=submit value=Upload>
        </form>
        '''

def bvep():
    return "vep on blueprint"

def register():
    return dict(
        vep = [
            dict(
                rule="/uploads/<filename>",
                view_func=uploaded_file
            ),
            dict(
                rule="/upload",
                view_func=upload_file,
                methods=["GET", "POST"]
            ),
            # Suppose a blueprint named test,
            # and the endpoint will be test.bvep(endpoint set it)
            dict(
                _blueprint="test",
                rule="/vep-on-blueprint",
                view_func=bvep,
            )
        ]
    )
  • 用户访问

访问/upload显示表单,访问上传的文件通过/uploads/filename