在AW上找不到Django/React app的静态文件

2024-05-18 11:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将Django/React应用程序部署到AWS。我有一个问题,服务器没有接收静态文件。我想我已经把所有的东西都配置好了,但是没有显示任何东西。我不确定我是否错过了一步,因为它似乎在Pytonyanywhere上工作正确,但不是AWS。

这是我的设置.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static') 

我运行^{cd1>}将文件生成到根目录。它输出^{cd2>}。

我在控制台中得到的错误如下^{cd3>}

我希望有人也有同样的问题,因为其他的解决方案,所以没有解决这个问题。这是当前的文件结构

^{pr2}$

Tags: 文件djangopy服务器aws应用程序urlos
1条回答
网友
1楼 · 发布于 2024-05-18 11:16:45

你用过Create React App吗?如果是这样,则必须配置your ^{}以指向正确的文件夹。在

因为我不知道你是Django的确切设置,这里有一些其他需要考虑的事情:

正确的URL(2.1语法)

urlpatterns += [
    re_path(r'(?P<path>.*)', TemplateView.as_view(template_name='index.html'), name='home')
]

更正静态文件URL:

^{pr2}$

正确的S3 Bucket配置:

# utils.py
from storages.backends.s3boto3 import S3Boto3Storage


def StaticRootS3BotoStorage(): return S3Boto3Storage(location='static')


def MediaRootS3BotoStorage(): return S3Boto3Storage(location='media')

以及

# conf.py

import os

from django.core.exceptions import ImproperlyConfigured


def get_env_variable(var_name):
    """Get the environment variable or return exception."""
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = 'Set the {} environment variable'.format(var_name)
        raise ImproperlyConfigured(error_msg)


AWS_ACCESS_KEY_ID = get_env_variable("ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = get_env_variable("SECRET_ACCESS_KEY")
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_STORAGE_BUCKET_NAME = get_env_variable("AWS_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = '%s.s3.eu-central-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_LOCATION = 'static'

STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
STATICFILES_STORAGE = 'config.settings.aws.utils.StaticRootS3BotoStorage'

DEFAULT_FILE_STORAGE = 'config.settings.aws.utils.MediaRootS3BotoStorage'
MEDIA_URL = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL

ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

作为参考,这是我使用的文件夹设置(以防您与路径斗争)。在aws中是conf.py和{}。在

enter image description here

相关问题 更多 >