使用 Flask Blueprint 可以将 Flask 应用程序分割为多个模块,每个模块可以具有自己的路由和视图函数。这样可以更好地组织和管理不同的服务。下面是一个示例代码,演示了如何使用 Flask Blueprint:
首先,在您的项目目录下创建一个名为 services 的文件夹,并在该文件夹下创建两个 Python 模块文件:service1.py 和 service2.py。
service1.py:from flask import Blueprintservice1_bp = Blueprint('service1', __name__)@service1_bp.route('/service1')def service1(): return 'Service 1'@service1_bp.route('/service1/hello')def service1_hello(): return 'Hello from Service 1'
service2.py:
from flask import Blueprintservice2_bp = Blueprint('service2', __name__)@service2_bp.route('/service2')def service2(): return 'Service 2'@service2_bp.route('/service2/hello')def service2_hello(): return 'Hello from Service 2'
接下来,在主模块中,将这两个 Blueprint 注册到应用程序中。

from flask import Flaskfrom services.service1 import service1_bpfrom services.service2 import service2_bpapp = Flask(__name__)# 注册 Blueprintapp.register_blueprint(service1_bp)app.register_blueprint(service2_bp)if __name__ == '__main__': app.run()
现在,您可以通过不同的 URL 路径访问不同的服务。例如,/service1 将访问 service1.py 中的服务,/service2 将访问 service2.py 中的服务。
使用 Flask Blueprint 可以方便地组织和管理不同的服务模块,每个模块可以有自己的路由和视图函数。这样可以使代码更加模块化、可维护和可扩展。您可以根据实际需求,创建多个 Blueprint,并在主模块中注册它们。