flask之蓝图BulePrint使用

之前flask启用程序代码和逻辑代码都是在一个页面,这样代码多了很自然不利于关于,如果要将逻辑代码和进行分离,这里需要用到Falsk的蓝图(Blueprint)

项目结构

app文件夹为项目最外层文件夹,web作为项目里的一个模块,

web下的articel和category文件为两个业务文件

如果需要articel和category文件能为正常注册访问,则需要使用蓝图来注册

在web下面新建__init__.py文件,里面相关代码

from flask import Blueprint
##实例化蓝图对象
web=Blueprint('web',__name__)
from app.web import article,category

app文件下面新建__init__.py文件
相关代码
from flask import Flask


##实例化全局app对象
def create_app():
    app = Flask(__name__)
    from app.web import web
    ##注册蓝图对象
    app.register_blueprint(web)

    return app

最外层app.y文件里相关代码:


from app import create_app

if __name__ == '__main__':

##调用创建实例对象
app=create_app()

app.run(port=5002, debug=True)

app/web下article.py相关代码
##导入__init.py文件下蓝图app对象
from app.web import web
from flask import render_template


@web.route('/article')
def list():
    return render_template('web/articel.html',message='this is article2 page')

@web.route('/')
def index():
    return render_template('web/articel.html',message='this is article page')

templates /web下article.html相关代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ message }}
</body>
</html>

启动项目访问127.0.0.1:5000

访问http://127.0.0.1:5000/article





猜你喜欢

转载自www.cnblogs.com/dongml/p/10909494.html