如何将任意参数传递给烧瓶蓝图? [英] How to pass arbitrary arguments to a flask blueprint?
问题描述
我有一个 Flask api,我已经将其包裹在一个对象中.这样做使单元测试变得轻而易举,因为我可以使用各种不同的设置实例化 api,具体取决于它是在生产中、测试中还是你有什么.
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 depending on whether it is in production, test, or whatehaveyou.
我现在正在尝试稍微扩展 api,为此我正在使用蓝图.问题是我无法弄清楚如何将参数传递给蓝图.我的路线需要诸如要访问哪个数据库之类的信息,而该信息不是静态的.如何将这些信息传递到蓝图中?我在下面包含了代码作为示例:
I am now trying to extend the api a bit, and for that I'm using a blueprint. The problem is that I cannot figure out how to pass arguments to the blueprint. My routes require information like which database to access, and that information is not static. How can I pass this information into a blueprint? I have included code below as an example:
api.py:
class MyApi(object):
def __init__(self, databaseURI):
self.app = Flask(__name__)
self.app.register_blueprint(myblueprint)
蓝图.py
myblueprint= Blueprint('myblueprint', __name__)
@myblueprint.route('/route', methods=['GET'])
def route():
database = OpenDatabaseConnection(databaseURI)
这里有一个相关的问题:如何将构造函数参数传递给 Flask 蓝图?
There is a related question here: How do I pass constructor arguments to a Flask Blueprint?
但是回答问题的人解决了操作的用例特定问题实际上回答了如何将任意参数传递给蓝图的问题.
But the people who answer the question solve the op's use-case specific problem without actually answering the question of how to pass arbitrary arguments to a blueprint.
推荐答案
您可以在构造函数中动态创建蓝图:
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)
这篇关于如何将任意参数传递给烧瓶蓝图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!