Flask路由注册route的几种方式

前言

Flask路由注册的三种方式:

  • app.route
  • app.add_url_rule
  • 蓝图

app.route(添加变量)

from flask import Flask


app = Flask(__name__)
app.config.from_pyfile('config/base_setting.py')
@app.route("/")
def hello():
    return "I Love jarvisyqliu"

@app.route("/my/")
def my(username):
    return "I Love test %s" % username

if __name__ == "__main__":
    app.run(host="0.0.0.0")

app.add_url_rule

from flask import Flask


app = Flask(__name__)
app.config.from_pyfile('config/base_setting.py')

# @app.route("/")
def hello():
    return "I Love jarvisyqliu"

# @app.route("/my/")
def my(username):
    return "I Love test %s" % username


app.add_url_rule(rule="/",view_func=hello)
app.add_url_rule(rule="/my/",view_func=my)


if __name__ == "__main__":
    app.run(host="0.0.0.0")

蓝图

from flask import Flask, Blueprint

index_page = Blueprint("index_page", __name__)

app = Flask(__name__)
app.config.from_pyfile('config/base_setting.py')

@index_page.route("/")
def hello():
    return "I Love jarvisyqliu"

@index_page.route("/my/")
def my(username):
    return "I Love test %s" % username

app.register_blueprint(index_page,url_prefix = "/test")


if __name__ == "__main__":
    app.run(host="0.0.0.0")

蓝图-分层管理

application.py

from flask import Flask
from index import index_page

app = Flask(__name__)
app.config.from_pyfile('config/base_setting.py')
app.register_blueprint(index_page, url_prefix="/test")

if __name__ == "__main__":
    app.run(host="0.0.0.0")

index.py

from flask import Blueprint

index_page = Blueprint("index_page", __name__)

@index_page.route("/")
def hello():
    return "I Love jarvisyqliu"

@index_page.route("/my/")
def my(username):
    return "I Love test %s" % username

你可能感兴趣的:(flask,python,后端)