Django paths, developing in windows, deploying on linux

江枫思渺然 提交于 2019-12-21 02:01:19

问题


I'm developing Django apps on my local windows machine then deploying to a hosted linux server. The format for paths is different between the two and manually replacing before deployment is consuming more time than it should. I could code based on a variable in my settings file and if statements but I was wondering if anyone had best practices for this scenario.


回答1:


The Django book suggests using os.path.join (and to use slashes instead of backslashes on Windows):

import os.path

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

I think this is the best solution as you can easily create relative paths like that. If you have multiple relative paths, a helper function will shorten the code:

def fromRelativePath(*relativeComponents):
    return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/")

If you need absolute paths, you should use an environment variable (with os.environ["MY_APP_PATH"]) in combination with os.path.join.




回答2:


We have a situation very similar to yours, and we've been using different paths in settings, basing on sys.platform. Something like this:

import os, sys
DEVELOPMENT_MODE = sys.platform == 'win32'
if DEVELOPMENT_MODE:
    HOME_DIR = 'c:\\django-root\\'
else:
    HOME_DIR = '/home/django-root/'

It works quite OK - assumed all development is being done on Windows.




回答3:


Add

import os.path

BASE_PATH = os.path.dirname(__file__)

at the top of your settings file, and then use BASE_PATH everywhere you want to use a path relative to your Django project.

For example:

MEDIA_ROOT = os.path.join(BASE_PATH, 'media')

(You need to use os.path.join(), instead of simply writing something like MEDIA_ROOT = BASE_PATH+'/media', because Unix joins directories using '/', while windows prefers '\')




回答4:


in your settings.py add the following lines

import os.path

SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))  
head, tail = os.path.split(SETTINGS_PATH)

#add some directories to the path
import sys
sys.path.append(os.path.join(head, "apps"))
#do what you want with SETTINGS_PATH


来源:https://stackoverflow.com/questions/2359187/django-paths-developing-in-windows-deploying-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!