将另一个对象传递给主烧瓶应用程序 [英] Pass another object to the main flask application

查看:115
本文介绍了将另一个对象传递给主烧瓶应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何以正确的方式将对象传递给烧瓶应用程序存在疑问。



这个想法很简单。



我想为我的应用程序创建一个api,这意味着由我的应用程序处理的http请求将触发主应用程序中的methds。

为此,我需要烧瓶来注意我的另一个过程,无论如何。



目前,我有这样的:

  if __name__ =='__main__':
Logger = MyProcess()
app.run()

我需要能够这样做:

  @ app.route('/ nb_trendy')
def nb_trendy():

res = Logger.get_trendy()
返回jsonify(res)

这意味着我要么给记录器的句柄给应用程序,或直接在应用程序中定义Logger。



但是在每个解决方案中,我都需要创建一个继承应用程序或者覆盖 __ init __() ,并将对象作为para米或修改 run() 方法。



它是这样的:

pre $ class $ MyFlask(Flask):
def __init __():
Flask。 __init __()
Logger = MyProcess()

这也是你要做的方式,还是有更好的方法来做到这一点?

谢谢!

这是一个更一般的版本这个问题: Flask中的Web API

解决方案

查看应用程序工厂 ,这应该做你想要的。您将创建一个返回您的Flask应用程序的工厂,您将发送记录器 - 如下所示:

  def create_app (logger_instance):
app = Flask(__ name__)
app.config ['LOGGER'] = logger_instance
return app

然后在你的runserver.py中创建并传入记录器:

  from yourapp import create_app $ b $ if if __name__ =='__main__':
logger = MyProcess()
app = create_app(logger)
app.run()

完成后,您的应用程序可以引用 app.config中的记录器[ 'LOGGER']


I got a doubt about how to pass an object to a flask app in the correct way.

The idea is simple.

I wan to create an api for my application, which means that http requests processed by my flask application will trigger meothds in my main application.

For that, I need flask to be aware of my other process, one way or another.

Currently, I have something like :

if __name__ == '__main__':
    Logger = MyProcess()
    app.run()

I need to be able to do something like that :

@app.route('/nb_trendy')
def nb_trendy():

    res = Logger.get_trendy()
    return jsonify(res)

which means that I either need to either give a handle on Logger to app, or directly define Logger inside app.

But in each of the solutions I can find, I need to create a that inherits app, to either override __init__() and takes objects as parameters, or modify the run() method.

the current way I would do it is though :

class MyFlask(Flask):
    def __init__():
        Flask.__init__()
        Logger = MyProcess()

Is this also the way you would do it, or is there a better way to do this?

Thanks!

Here is a more general version of this question: Web API in Flask

解决方案

Take a look at application factories, which should do what you're looking for. You'd create a factory that returned your Flask app that you'd send the logger to - something like this:

def create_app(logger_instance):
    app = Flask(__name__)
    app.config['LOGGER'] = logger_instance
    return app

And then in your runserver.py, you'd create and pass in the logger:

from yourapp import create_app
if __name__ == '__main__':
    logger = MyProcess()
    app = create_app(logger)
    app.run()

Once that's done, your app can refer to the logger inside app.config['LOGGER'].

这篇关于将另一个对象传递给主烧瓶应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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