How to pass arbitrary arguments to a flask blueprint?

前端 未结 2 1467
挽巷
挽巷 2020-12-16 01:59

I have a flask api which I have wrapped up in an object. Doing this has made unit testing a breeze, because I can instantiate the api with a variety of different settings de

相关标签:
2条回答
  • 2020-12-16 02:21

    This way it's possible to add a blueprint, passing parameters, inside an appfactory. Sometimes you'll need it and it's not described anywhere in the flask docs.

    Assuming bp1.py, bp2.py are in the same folder as your appname

    from appname import bp1, bp2
    
    app.register_blueprint(bp1.bp)
    # with parameters:
    app.register_blueprint(bp2.construct_blueprint(arg1, arg2))
    

    inside bp2.py:

    def construct_blueprint(arg1, arg2):
        bp = Blueprint("bp2", __name__)
    
        @bp.route('/test')
        def test():
            ret = {'arg1': arg1, 'arg2': arg2}
            return jsonify(ret)
    
        return bp
    
    0 讨论(0)
  • 2020-12-16 02:33

    You could create the blueprint dynamically in a constructor function:

    def construct_blueprint(database):
    
        myblueprint = Blueprint('myblueprint', __name__)
    
        @myblueprint.route('/route', methods=['GET'])
        def route():
            database = database
    
        return(myblueprint)
    
    0 讨论(0)
提交回复
热议问题