flask 中使用藍圖將路由分開寫在不同文件


flask 若想將不同的路由寫在不同的文件中(如將 user 對象的相關接口寫在一個文件中,將 customer 對象的相關接口寫在另一個文件中),可以使用藍圖來實現。

有關藍圖的定義:A Blueprint is a way to organize a group of related views and other code.

更多信息詳見:http://flask.pocoo.org/docs/1.0/tutorial/views/#create-a-blueprint

都說自己寫的博客自己也不一定會常看,出了問題互聯網上總能找到相關信息。但總知:

輟學,如磨刀之石,不見其損,日有所虧!

故還是記錄一下自己的解決方法,既當總結,若能方便他人也甚好。


假設有兩個模型,usercustomer, 分別將有關他們的視圖函數寫在兩個不同的文件中:

  • user_opt.py

from model import User
from flask import Blueprint
user_opt = Blueprint('user_opt', __name__)
​
# 查(按名字查)
@user_opt.route('/query_name/<user_name>', methods=['GET'])
def query_by_name(user_name):
    users = User.query.filter(User.name == user_name).all()
    return users
  • customer_opt.py

from model import Customer
from flask import Blueprint
customer_opt = Blueprint('customer_opt', __name__)
​
# 查(按 id 查)
@customer_opt.route('/query_id/<customer_id>', methods=['GET'])
def query_by_id(customer_id):
    customer = Customer.query.filter(Customer.id == customer_id).first()
    return customer

新建的 flask 工程均有 manage.py 文件,寫好了上面兩個接口之后,若想在 flask 運行時可以直接訪問不在 manage.py 中的接口,還需要手動將上面寫好的兩個藍圖進行注冊:

  • manage.py

from flask import Flask
import config
from exts import db
from user_opt import user_opt
from customer_opt import customer_opt
​
app = Flask(__name__)
# 注冊藍圖,並指定其對應的前綴(url_prefix)
app.register_blueprint(user_opt, url_prefix="/user_opt")
app.register_blueprint(customer_opt, url_prefix="/customer_opt")
​
# 引入配置文件中的相關配置
app.config.from_object(config)
# 配置db
db.init_app(app)
​
​
@app.route('/')
def hello_world():
    return 'Hello World!'if __name__ == '__main__':
    app.run(host="127.0.0.1", port=5000, debug=True)

此時,運行 flask 項目,在瀏覽器中輸入:

http://127.0.0.1:5000/user_opt/query_id/1
# 通過前綴 user_opt 訪問 user 中的相關接口
http://127.0.0.1:5000/customer_opt/query_name/xiaoming
# 通過前綴 customer_opt 訪問 customer 中的相關接口

【參考文章】:flask中使用藍圖將路由分開寫在不同文件實例解析


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM