如何在Flask中共享全局应用程序对象? [英] How to share the global app object in flask?

查看:411
本文介绍了如何在Flask中共享全局应用程序对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用烧瓶,并尝试执行以下操作.

I am using flask and trying to the following.

我已经定义了一个main.py文件,通过该文件我可以运行我的应用程序,即python main.py-

I have defined a main.py file through which I want to run my app ie python main.py -

from flask import Flask
from view import tags

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

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

我已经定义了一个名为view的程序包,其中将声明不同的view模块,每个模块都有自己的路由. view.tags.py-

I have defined a package named view in which I will be declaring my different view modules, each having its own routes. view.tags.py -

from flask import Flask
app = Flask(__name__)

@app.route('/e')
def hello_world2():
    return 'Hello World!'

因此,我需要在main.py中拥有用于运行服务器的全局应用程序对象,以及在程序包的视图类中具有用于注册路由的全局对象.那么,如何创建全局应用程序对象并在所有类之间共享呢?

So I need to have the global app object in my main.py for running the server, as well as in the view classes of my package for registering the routes. So how do I create the global app object and share it between all classes ?

谢谢, 穆尔塔扎

推荐答案

一种方法是创建一个整体程序包,并在声明所有全局变量的位置下添加一个__init__.py文件.以您的情况为例,您可以创建以下内容:

One way is to create an overall package and adding a __init__.py file under that where you declare all global variables. In your case for example, you can create something like:

myapplication/
    *        __init__.py
    *        myviews/
        *         __init__.py
        *         view.py
        *         tags.py

现在,在__init__.py文件中添加以下代码:

Now you add the following code in the __init__.py file:

app = Flask(__name__)

现在,只要导入包myapplication,就可以在任何地方使用此应用程序变量.

You can now use this app variable anywhere as long as you import the package myapplication.

import myapplication.myviews.view

这篇关于如何在Flask中共享全局应用程序对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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