Nested Blueprints in Flask?

后端 未结 3 1136
囚心锁ツ
囚心锁ツ 2020-12-09 17:54

I\'m still new to Flask, so there may be an obvious way to accomplish this, but I haven\'t been able to figure it out so far from the documentation. My app is divided into s

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 18:48

    I made a class called NestedBlueprint to hack it.

    class NestedBlueprint(object):
        def __init__(self, blueprint, prefix):
            super(NestedBlueprint, self).__init__()
            self.blueprint = blueprint
            self.prefix = '/' + prefix
    
        def route(self, rule, **options):
            rule = self.prefix + rule
            return self.blueprint.route(rule, **options)
    

    Here is my base file which contains the blueprint: panel/__init__.py

    from flask import Blueprint
    
    panel_blueprint = Blueprint(PREFIX, __name__, url_prefix='/panel')
    
    from . import customize
    

    Here is the specific/nested file which contains nested blueprint: panel/customize.py

    from rest.api.panel import panel_blueprint
    from rest.api.util.nested_blueprint import NestedBlueprint
    
    nested_blueprint = NestedBlueprint(panel_blueprint, 'customize')
    
    
    @nested_blueprint.route('/test', methods=['GET'])
    def test():
        return ':)'
    

    You can then call like this:

    $ curl http://localhost:5000/panel/customize/test
    :)
    

提交回复
热议问题