前言
Flask路由注册的三种方式:
- app.route
- app.add_url_rule
- 蓝图
app.route(添加变量)
from flask import Flaskapp = Flask(__name__)
app.config.from_pyfile('config/base_setting.py')
@app.route("/")
def hello():return "I Love jarvisyqliu"@app.route("/my/<username>")
def my(username):return "I Love test %s" % usernameif __name__ == "__main__":app.run(host="0.0.0.0")
app.add_url_rule
from flask import Flaskapp = Flask(__name__)
app.config.from_pyfile('config/base_setting.py')# @app.route("/")
def hello():return "I Love jarvisyqliu"# @app.route("/my/<username>")
def my(username):return "I Love test %s" % usernameapp.add_url_rule(rule="/",view_func=hello)
app.add_url_rule(rule="/my/<username>",view_func=my)if __name__ == "__main__":app.run(host="0.0.0.0")
蓝图
from flask import Flask, Blueprintindex_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/<username>")
def my(username):return "I Love test %s" % usernameapp.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_pageapp = 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 Blueprintindex_page = Blueprint("index_page", __name__)@index_page.route("/")
def hello():return "I Love jarvisyqliu"@index_page.route("/my/<username>")
def my(username):return "I Love test %s" % username