如何将任意参数传递给瓶蓝图? [英] How to pass arbitrary arguments to a flask blueprint?
问题描述
我正在尝试扩展api,为此我使用蓝图。问题是,我无法弄清楚如何将论据传递给蓝图。我的路线需要像访问哪个数据库的信息,而且这些信息不是静态的。我怎样才能将这些信息转化为蓝图?我已经将下面的代码作为例子:
api.py:
class MyApi(object):
def __init __(self,databaseURI):
self.app = Flask(__ name__)
self.app.register_blueprint(myblueprint)
blueprint.py
myblueprint = Blueprint('myblueprint',__name__)
@ myblueprint.route('/ route',methods = ['GET'])
def route():
database = OpenDatabaseConnection(databaseURI )
这里有一个相关的问题:
如何将构造函数参数传递给Flask Blueprint?
但是回答问题的人解决了op的用例特定问题,而没有真正回答如何将任意参数传递给蓝图的问题。
<您可以在构造函数中动态地创建蓝图:
def construct_blueprint(database):
myblueprint = Blueprint('myblueprint',__name__)
@ myblueprint.route('/ route',methods = ['GET'])
def route():
database = database
return(myblueprint)
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.
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)
blueprint.py
myblueprint= Blueprint('myblueprint', __name__)
@myblueprint.route('/route', methods=['GET'])
def route():
database = OpenDatabaseConnection(databaseURI)
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屋!