python - 静态文件未在生产中显示

标签 python django nginx gunicorn

已编辑以显示更新的配置

生产中没有显示静态文件。文件在开发中正确显示

settings.py

BASE_DIR = os.path.dirname(__file__)

STATIC_ROOT = '/opt/soundshelter/static/'

print "Base Dir: " + BASE_DIR #this returns /opt/soundshelter/soundshelter/soundshelter
print "Static Root: " + STATIC_ROOT #this returns /opt/soundshelter/static/


STATIC_URL = '/static/'

STATICFILES_DIRS = (

    os.path.join(BASE_DIR, 'static'),

) #/opt/soundshelter/soundshelter/soundshelter/static

应用程序中正在调用文件 <link href="{% static "css/portfolio-item.css" %}" rel="stylesheet">

使用 Nginx 和 Gunicorn。

Nginx 配置:

server {
    server_name 46.101.56.50;

    access_log yes;

    location /static {
        autoindex       on;
        alias /opt/soundshelter/static/;
}

    location / {

        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }

#       error_log /opt/soundshelter/soundshelter/soundshelter/nginx-error.log;

}

正在运行python manage.py collectstatic报告文件已成功复制,但仍未显示。

由 Fabric 处理的部署

from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm

env.hosts = []

print "Here we go..."

def commit():
    local("git add . && git commit")

def push():
    local("git push origin master")

def prepare_deploy():

    commit()
    push()

def deploy():
    code_dir = '/opt/soundshelter/soundshelter/'
    with cd(code_dir):
        run("git pull")
        run("python manage.py collectstatic -v0 --noinput")
        run("service nginx restart")
        run("ps aux |grep gunicorn |xargs kill -HUP")
        run("gunicorn -b PROD_IP soundshelter.wsgi:application")

commit()
push()
deploy()

最佳答案

首先,在我看来,您编辑的 STATICFILES_DIRS 指向错误的文件夹,因为您有 /static/ 文件夹,而不是 /staticfiles/。应该是原来的样子:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

其次,STATIC_ROOT 应指向将由 pro 中的网络服务器提供服务的静态文件夹(但最好不在项目文件夹中)。对于您的情况:

STATIC_ROOT="/opt/soundshelter/soundshelter/soundshelter/static/"

我通常将静态文件夹放在项目附近,并使用动态STATIC_ROOT而不是硬编码:

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
#this will alow to collect your static files in /opt/soundshelter/soundshelter/staticfiles/static
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles/static')

现在您应该执行collectstatic,它将收集STATIC_ROOT 目录中的所有静态文件。

关于python - 静态文件未在生产中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33051578/

相关文章:

python - 从 Python 列表中删除 nan 值

python - 如何展平解析树并存储在字符串中以进行进一步的字符串操作python nltk

python - Azure Database for PostgreSQL 灵活服务器使用 Django 速度缓慢

nginx - Nginx在上游响应日志中显示2种不同的状态

Python:操作列表

python - subprocess.communicate() 仅在从脚本运行时神秘地挂起

python - 在 Django 中添加自定义字段的最佳实践

Django + uwsgi + nginx + SSL

docker - Nginx 无法在 docker 容器中加载证书

docker - 努力将Nginx代理+ LetsEncrypt伴侣与我的Docker组成的Web应用程序集成