2016-08-25 64 views
0

我基于我在github上发现的Web应用程序的结构,here烧瓶无法在父目录中找到配置模块

我的项目的结构是这样的:

~/Learning/flask-celery $ tree 
. 
├── config 
│   ├── __init__.py 
│   └── settings.py 
├── docker-compose.yml 
├── Dockerfile 
├── requirements.txt 
└── web 
    ├── app.py 
    ├── __init__.py 
    ├── static 
    └── templates 
     └── index.html 

我想在我的web/app.py瓶应用的config模块加载设置,正如我在上面链接的githug项目看到的。

这里是我如何在实例中web/app.py瓶应用:

from flask import Flask, request, render_template, session, flash, redirect, url_for, jsonify 

[...] 

app = Flask(__name__, instance_relative_config=True) 

app.config.from_object('config.settings') 
app.config.from_pyfile('settings.py') 

[...] 

,我发现了问题:

[email protected]:/usr/src/app# python3 web/app.py 
Traceback (most recent call last): 
    File "/usr/local/lib/python3.5/site-packages/werkzeug/utils.py", line 427, in import_string 
    module = __import__(module_name, None, None, [obj_name]) 
ImportError: No module named 'config' 
[...] 

显然,瓶找不到在该config模块父目录,这让我很感兴趣,但我不明白我所依赖的链接项目是如何使用相同的树结构和Flask配置代码成功加载模块的。

在这些情况下,我该如何让Flask加载config模块?

回答

2

如果不将config目录添加到您的路径中,您的Python包将无法看到它。

您的代码只能通过它的外观访问web中的内容。

您可以添加config目录的包像这样:

import os 
import sys 
import inspect 

currentdir = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe()))) 
parentdir = os.path.dirname(currentdir) 
sys.path.insert(0, parentdir) 

那么你应该能够导入配置。

+0

感谢您的回答。我会试试看,它看起来应该可以工作,但我很好奇连接的github项目是如何工作的呢?我认为'instance_relative_config = True'意味着它会看起来在我的根。 – Juicy

+0

http://flask.pocoo.org/docs/0.11/config/#instance-folders不确定为什么你的即时工作可能与它的运行方式有关。 –

相关问题