简体   繁体   English

在 Heroku 中提供 Static 文件

[英]Serving Static Files in Heroku

I have a Django and React app hosted on Heroku, the issue is that it does not see my files but everything is completely working in my localhost.我有一个 Django 和 React 应用程序托管在 Heroku 上,问题是它看不到我的文件,但一切都在我的本地主机中完全正常工作。 It was built successfully on Heroku.它在 Heroku 上成功构建。

Debugging process:调试过程:

Project built successfully项目搭建成功

已部署的项目

Opens App打开应用

Returns a blank page meaning it is not serving my CSS and js files.返回一个空白页,表示它不提供我的 CSS 和 js 文件。

空白应用

Checked Developer tools已检查的开发人员工具

The Django app requires the CSS and js files to show the template Django 应用程序需要 CSS 和 js 文件来显示模板

开发者工具

Checked Heroku logs检查 Heroku 日志

Heroku returns err 404 for those files Heroku 为这些文件返回 err 404

Heroku 日志

Check my Deployed files in Heroku检查我在 Heroku 中部署的文件

I checked to see my files that are deployed in Heroku in my terminal, and they are there.我检查了我在终端中部署在 Heroku 中的文件,它们就在那里。

Heroku 部署的文件

Setting环境

import django_heroku
import os
from datetime import timedelta
from pathlib import Path
from decouple import config

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = config('SECRET_KEY')

DEBUG = True

ALLOWED_HOSTS = ['*']


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'corsheaders',
    'storages',
    'cloudinary_storage',
    'cloudinary',

    'base.apps.BaseConfig',
]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}


SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'frontend/build')
        ],
        '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 = 'backend.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'
MEDIA_URL = '/click2buy/'

STATICFILES_DIRS = [
    BASE_DIR / 'static',
    BASE_DIR / 'frontend/build/static'
]


MEDIA_ROOT = BASE_DIR / 'static/images'
STATIC_ROOT = BASE_DIR / 'staticfiles'

DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'

CORS_ALLOW_ALL_ORIGINS = True

if os.getcwd() == '/app':
    DEBUG = False

CLOUDINARY_STORAGE = {
    'CLOUD_NAME': config('CLOUD_NAME'),
    'API_KEY': config('API_KEY'),
    'API_SECRET': config('API_SECRET'),
}

django_heroku.settings(locals())

Now, I'm confused, why is it not serving the files, it's not a code problem cos everything is working well in my localhost.现在,我很困惑,为什么它不提供文件,这不是代码问题,因为在我的本地主机中一切都运行良好。 Any solutions pls?有什么解决方案吗? Thanks.谢谢。

One Thing you need to understand that Heroku does not provide support to serve your static files you need to use tools like s3 bucket to server static files one more issue i find that your database i have used aws rds free version postgres database by which you can solve your query here is the video which might help you what you are lacking One Thing you need to understand that Heroku does not provide support to serve your static files you need to use tools like s3 bucket to server static files one more issue i find that your database i have used aws rds free version postgres database by which you can在这里解决您的查询是视频,它可能会帮助您您所缺乏的

good Luck祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM