flask 插拨式视图

xiaoxiao2021-02-28  65

为了我们的视图能够方便的复用,我们有必要学习一下flask的插拨式视图

首先我们需要从flask.view导入MethodView类,该类能够轻松的实现不同的HTTP方法,比如本例中的“GET”方法,当然我们也可以定义“POST”、“PUT”等方法。 然后我们定义一个IndexView类,定义“GET”方法的视图函数get(),让它返回我们想要的功能。(maple-master/forums/views.py)

from flask.views import MethodView class IndexView(MethodView): def get(self): return "<h1>Hollo World</h1>"

然后我们使用蓝图注册路由(maple-master/forums/urls.py) 这里我们用了add_url_rule方法添加路由。

from flask import Blueprint from .views import IndexView site = Blueprint('forums', __name__) site.add_url_rule('/', view_func=IndexView.as_view('index'))

最后注册蓝图(maple-master/forums/_init_.py)

from flask import Flask from forums.urls import site import os def create_app(config): templates = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, 'templates')) static = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, 'static')) app = Flask(__name__, template_folder=templates, static_folder=static) app.config.from_object(config) register(app) return app # 定义一个注册函数 # url_prefix参数为url增加一个前缀 def register(app): app.register_blueprint(site, url_prefix='/site')

最后启动服务(maple-master/runserver.py)

from forums import create_app app = create_app('config') if __name__ == '__main__': app.run(debug=True)

浏览器打开http:127.0.0.1:5000/site 就能看到“Hollo World”了

项目结构: maple-master │ config.py │ runserver.py │ ├─forums │ │ urls.py │ │ views.py │ │ init.py │ │ │ └─pycache │ urls.cpython-35.pyc │ views.cpython-35.pyc │ init.cpython-35.pyc │ ├─static ├─templates └─pycache config.cpython-35.pyc runserver.cpython-35.pyc

转载请注明原文地址: https://www.6miu.com/read-74050.html

最新回复(0)