简体   繁体   English

如何访问应用程序之外的烧瓶应用程序配置?

[英]How can I access the flask application configuration outside of the application?

I'm not sure if this is a flask specific issue or if I simply lack an understanding of the python import mechanism, but I'm having some problems with a flask web application. 我不确定这是否是特定于烧瓶的问题,或者我是否只是缺乏对python导入机制的理解,但我对烧瓶Web应用程序有一些问题。 Here's the layout of my application: 这是我的应用程序的布局:

/myapp
  /INSTALL
  /TODO
  /run.py
  /instance
    /application.cfg
  /myapp
    /static
    /templates
    /__init__.py
    /config.py
    /service.py

The config.py file stores the default application configuration, and application.cfg stores instance configuration. config.py文件存储默认应用程序配置,application.cfg存储实例配置。 They both look like this: 它们看起来都是这样的:

DEBUG = False
TESTING = False
SECRET_KEY = "please_replace_me"

This is how I set up the application in init .py: 这是我在init .py中设置应用程序的方法:

import flask
app = Flask(__name__, instance_relative_config=True)
app.config.from_object("myapp.config")
app.config.from_pyfyle("application.cfg", silent=True)

Now what I want is to access the app.config object from service.py, which is not included by init .py or any of the other modules that are part of the web application. 现在我想要的是从service.py访问app.config对象,该对象不包含在init .py或Web应用程序中的任何其他模块中。 Ie this is how I want my service.py file to read: 也就是我希望我的service.py文件阅读:

from somewhere.somehow import app

def run():
  do_stuff(app.config["CONFIG_OPTION"])

The problem is the service.py file has to be inside the package, so I can't move it one folder up and just import myapp. 问题是service.py文件必须在包内,所以我不能将它移动到一个文件夹,只需导入myapp。 How do I do this? 我该怎么做呢?

Python relative imports are relative to __main__ . Python相对导入与__main__

If I assume correctly your run.py is the __main__ . 如果我假设你的run.py__main__ In that case you should be able to do: 在这种情况下,您应该能够:

from myapp import app

If you want to import the module which is located in the parent directory, one possible way to do it is to add the parent directory to sys.path before importing: 如果要导入位于父目录中的模块,一种可能的方法是在导入之前将父目录添加到sys.path:

cmd_folder = os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe() ))[0])
sys.path.append(cmd_folder+'/../')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM