当我启动本地开发服务器(./manage runserver
)时,settings.py运行四次。我注意到了,因为错误/调试消息被打印了四次。
有什么想法可以来吗?我甚至不知道从哪里开始寻找。这对我很重要,因为我正在努力设置Sentry,它不会按照现在安装的方式报告网站的任何错误。
更新:
我检查了导入的模块import settings
,我的应用中没有。
然后我添加了
import traceback; traceback.print_stack(); print
到settings.py。结果是:
File "./manage.py", line 5, in <module>
import settings # Assumed to be in the same directory.
File "(...)/myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
File "./manage.py", line 12, in <module>
execute_manager(settings)
(...)
File "(...)/site-packages/django/conf/__init__.py", line 73, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "(...)/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "(...)/myapp/../myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
File "./manage.py", line 5, in <module>
import settings # Assumed to be in the same directory.
File "(...)/myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
File "./manage.py", line 12, in <module>
execute_manager(settings)
(...)
File "(...)/site-packages/django/conf/__init__.py", line 73, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "(...)/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "(...)/myapp/../myapp/settings.py", line 4, in <module>
import traceback; traceback.print_stack(); print
这是预期的行为吗?如果没有,我怎么能找到我的错误?
答案 0 :(得分:3)
通过sys.path
中的不同条目访问它。你永远不应该尝试导入settings
;改为导入django.conf.settings
。
答案 1 :(得分:2)
这种行为实际上发生在全新的Django 1.3项目中。首次启动开发服务器时,它会执行四次导入:
$ django-admin.py startproject test_project
$ cd test_project/
# settings.py
print "importing settings.py"
...
$ python manage.py runserver
importing settings.py
importing settings.py
importing settings.py
importing settings.py
Validating models...
0 errors found
Django version 1.3, using settings 'test_project.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
如果在运行开发服务器的情况下编辑文件,则只执行两次导入:
$ touch settings.py
输出:
importing settings.py
importing settings.py
Validating models...
0 errors found
Django version 1.3, using settings 'test_project.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
我不确定它为什么这样做,或者它是否在非开发服务器上执行此操作。但这种行为似乎是正常的。
如果您在settings.py中跟踪导入,则不会在多个导入中保留值:
# settings.py
import_count = 0
import_count += 1
print "import count: %d" % import_count
重新开始:
$ python manage.py runserver
import count: 1
import count: 1
import count: 1
import count: 1
Validating models...
更改了文件:
import count: 1
import count: 1
Validating models...
所以也许只是阅读文件来配置自己,并在最后一次导入并实际使用之前验证一切正常?