如何将任意参数传递给瓶蓝图? [英] How to pass arbitrary arguments to a flask blueprint?

查看:355
本文介绍了如何将任意参数传递给瓶蓝图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个瓶子,我已经包裹在一个物体。这样做使得单元测试变得轻而易举,因为我可以根据是否在生产,测试或whatehaveyou中,以各种不同的设置来实例化api。

我正在尝试扩展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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆