如何根据是开发服务器还是生产服务器使用不同的静态文件位置

How to use different staticfiles location based on if it is development or production server

这是我的 settings.py:

import os
import sys
SECRET_KEY = 'secrit'

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
if RUNNING_DEVSERVER:
    DEBUG = True
else:
    DEBUG = False

ALLOWED_HOSTS = ['127.0.0.1', 'ebdjangoapp-dev.us-east-1.elasticbeanstalk.com']


INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'ebdjangoapp',
    'storages',
)


AWS_HEADERS = {  # see http://developer.yahoo.com/performance/rules.html#expires
        'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
        'Cache-Control': 'max-age=94608000',
    }

AWS_STORAGE_BUCKET_NAME = 'ebdjangoappstaticfiles'
AWS_ACCESS_KEY_ID = 'key'
AWS_SECRET_ACCESS_KEY = 'secritkey'

# Tell django-storages that when coming up with the URL for an item in S3 storage, keep
# it simple - just use this domain plus the path. (If this isn't set, things get complicated).
# This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it.
# We also use it in the next setting.
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

STATICFILES_LOCATION = 'static'

# This is used by the `static` template tag from `static`, if you're using that. Or if anything else
# refers directly to STATIC_URL. So it's safest to always set it.
if RUNNING_DEVSERVER:
    STATIC_URL = '/static/'
else:
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

# Tell the staticfiles app to use S3Boto storage when writing the collected static files (when
# you run `collectstatic`).
STATICFILES_STORAGE = 'ebdjangoapp.custom_storages.StaticStorage'

MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'ebdjangoapp.custom_storages.MediaStorage'


MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'ebdjango.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "ebdjangoapp/static/templates/")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ebdjango.wsgi.application'


if 'RDS_DB_NAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }
else:
    # Default Django
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }



LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, "static")

我按照这个 URL https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ 来让亚马逊服务器我的静态和媒体文件。它在生产中完美运行。我决定停止我的生产服务器,直到我完全测试开发中的所有内容。

我认为这些行在我的 settings.py 文件中:

RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver')
# ...
if RUNNING_DEVSERVER:
    STATIC_URL = '/static/'
else:
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

将允许我的开发服务器在 app 目录的 static 文件夹中查找静态文件。我做了 python manage.py runserver 然后去了 127.0.0.1,当我检查元素时,显示了这些错误:

GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/home.js 
home:11 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/bootstrapCSS/css/bootstrap.min.css 
home:12 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/js/bootstrapJS/bootstrap.min.js 
home:15 GET https://ebdjangoappstaticfiles.s3.amazonaws.com/static/css/home.css

当我尝试导入 CSS 文件时,我在模板中这样做:

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}">

我还需要更改哪些内容才能使其不搜索 https://ebdjangoappstaticfiles.s3.amazonaws.com 我的静态文件?

您的 if 声明是正确的,但是,您的 argv 方法 非常 脆弱。例如,您可以 运行 与 python manage.py runservermanage.py runserver 相同的脚本,更改参数顺序并破坏您的逻辑。

相反,您可以使用两种更可靠的方法;最简单的方法是使用 DEBUG 设置来确定您是在开发中还是在生产中。

if DEBUG:
    # assume we're local
else:
    # otherwise assume we're in production

然后您只需要确保在生产中设置 DEBUG = False,无论如何您都应该非常小心。

如果您有多个环境,例如 QA 服务器、暂存服务器和生产服务器,明智的做法是使用环境变量并将其导入到您的设置中。

import os

# get environment variable ENV from the system
# default to prod if it doesn't exist
ENV = os.getenv('ENV', 'prod')

if ENV == 'local':
    # use local settings
elif ENV == 'stage':
    # use staging settings
else:
    # assume we're in prod

然后您可以在每个环境中设置 ENV 环境变量以匹配它们的角色(localdevqastage , prod, 等等)。这样你就不需要改变你的设置文件来翻转变量。

最后一个方便的技巧是您可以通过根据变量有选择地导入它们来级联设置文件。

ENV = os.getenv('ENV', 'prod')

SOME_SETTING = 'no.png'

if ENV == 'local':
    import settings_local # could override SOME_SETTING
else:
    import settings_prod # could also override SOME_SETTING

你走在正确的道路上。您需要做的就是设置 STATICFILES_STORAGE.

if DEBUG:
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
    STATIC_URL = "/static/"
else:
    STATICFILES_STORAGE = "backend.storage_backends.StaticStorage"
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)