Python Django-如何在协作项目上处理settings.py中的路径
我刚刚开始为我的公司进行Django的可行性研究,我注意到settings.py上需要绝对路径:Python Django-如何在协作项目上处理settings.py中的路径,python,django,Python,Django,我刚刚开始为我的公司进行Django的可行性研究,我注意到settings.py上需要绝对路径: TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
我的问题是:在与团队合作时,如何处理这些绝对路径?比方说,如果团队成员在从源代码管理获取项目后必须修改路径,这不仅容易出错,而且浪费时间,而且在该用户必须提交对settings.py所做的更改时,还会导致复杂性。如何避免这种情况?
settings.py
只是另一个Python模块。导入并使用中的各种函数来构建路径。执行以下操作:
import os
ROOT_PATH = os.path.dirname(__file__)
.
.
.
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates'),
)
这将根据settings.py文件的目录设置路径
import os.path
#Get the absolute path of the settings.py file's directory
PWD = os.path.dirname(os.path.realpath(__file__ ))
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#Add Templates to the absolute directory
os.path.join(PWD, "Templates")
)
这就是我做相对进口的方式。请注意,通常明智的做法是使用单独的localsettings.py文件或类似文件。除了使用settings.py文件中的相对路径外,每个开发人员都有自己的settings.py
# settings.py
TEMPLATE_DIRS = (
'c:\django\templates\',
)
# dev-x-settings.py
import settings
TEMPLATE_DIRS = (
'd:\dev\django\project\templates\'
)
dev-x-settings.py从基本文件导入所有设置,并更改它们需要的位和块。对于维护本地sqlite数据库等也非常方便
我们通常设置为:
/settings/
__init__.py
production.py
staging.py
test.py
dev-x.py
dev-y.py
然后,您需要担心的就是运行服务器并将正确的settings.py文件传递给它。除了使用
os.path之外,您还可以添加
try:
import * from settings_local
except:
pass
在您的settings.py
末尾。然后,每个开发人员都可以创建自己的设置\u local.py
文件,该文件未签入VCS 为什么默认的PWD=os.path.dirname(os.path.dirname(_文件__))
?有什么不同吗?请注意,在Windows上,此方法将创建具有反斜杠的路径,这与Django文档(例如,和上面代码段中的注释)相反。