尝试将我的代码从github推送到Heroku,在设置了S3的静态之后。我正在使用Django。
我尝试了不同的解决方案,我发现在这里,但没有成功。
下面是我做过的不同的事情。
1.删除了显然与django-storages
不兼容的whitenoise
;
1.我还测试了以下combo,它没有返回任何错误。
pythonmanage.py静态
Pythonmanage.py测试
我确实设法用$ heroku config:set DISABLE_COLLECTSTATIC=1
把代码推到了heroku,但是明显的静态信息不存在。
最后,一个帖子建议运行heroku run 'bower install --config.interactive=false;grunt prep;python manage.py collectstatic --noinput'
,但这只会给我带来一个错误消息C:\Program' is not recognized as an internal or external command,operable program or batch file
。
在代码方面,我有一个名为Settings
的文件,其中有base.py
、prod.py
和dev.py
。
基本.py
import os
from pathlib import Path
import django_heroku
import dj_database_url
from decouple import config
from dotenv import load_dotenv, find_dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"crispy_forms",
'main.apps.MainConfig',
'django_extensions',
'storages',
'import_export',
'django.contrib.sites',
'fontawesomefree',
]
MIDDLEWARE = [
'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 = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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',
'django.template.context_processors.request',
],
'libraries' : {
'staticfiles': 'django.templatetags.static',
}
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
load_dotenv(find_dotenv())
DATABASES = {'default': dj_database_url.config(default='sqlite:///db.sqlite3',conn_max_age=600)}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10240 # higher than the count of fields
#storing static files
VENV_PATH = os.path.dirname(BASE_DIR)
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
django_heroku.settings(locals())
AUTHENTICATION_BACKENDS = [
]
偏差py
from .base import *
SECRET_KEY = XXX
DEBUG = True
ALLOWED_HOSTS = ['*' ]
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
生产年度
from .base import *
from decouple import config
import django_on_heroku
SECRET_KEY = config('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = ['mysite.herokuapp.com', ]
# Amazon AWS S3 Settings
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = ('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_OBJECT_PARAMETERS ={
'CacheControl':'max-age=86400'
}
AWS_LOCATION = 'static'
AWS_QUERYSTRING_AUTH = False
AWS_HEADERS = {'Access-Control-Allow-Origin':'*'}
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'
# Heroku Logging
DEBUG_PROPAGATE_EXCEPTIONS = True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'MYAPP': {
'handlers': ['console'],
'level': 'DEBUG',
},
}
}
# Heroku Settings
django_on_heroku.settings(locals(), staticfiles=False)
del DATABASES['default']['OPTIONS']['sslmode']
回溯
-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/python
-----> Python app detected
-----> Using Python version specified in runtime.txt
-----> No change in requirements detected, installing from cache
-----> Using cached install of python-3.10.8
-----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1
-----> Installing SQLite3
-----> Installing requirements with pip
-----> $ python manage.py collectstatic --noinput
Traceback (most recent call last):
File "/tmp/build_a1a18ada/manage.py", line 22, in <module>
main()
File "/tmp/build_a1a18ada/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle
collected = self.collect()
File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect
handler(path, prefixed_path, storage)
File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 378, in copy_file
self.storage.save(prefixed_path, source_file)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/files/storage.py", line 57, in save
name = self._save(name, content)
File "/app/.heroku/python/lib/python3.10/site-packages/storages/backends/s3boto3.py", line 457, in _save
obj.upload_fileobj(content, ExtraArgs=params, Config=self._transfer_config)
File "/app/.heroku/python/lib/python3.10/site-packages/boto3/s3/inject.py", line 725, in object_upload_fileobj
return self.meta.client.upload_fileobj(
File "/app/.heroku/python/lib/python3.10/site-packages/boto3/s3/inject.py", line 636, in upload_fileobj
return future.result()
File "/app/.heroku/python/lib/python3.10/site-packages/s3transfer/futures.py", line 103, in result
return self._coordinator.result()
File "/app/.heroku/python/lib/python3.10/site-packages/s3transfer/futures.py", line 266, in result
raise self._exception
File "/app/.heroku/python/lib/python3.10/site-packages/s3transfer/tasks.py", line 139, in __call__
return self._execute_main(kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/s3transfer/tasks.py", line 162, in _execute_main
return_value = self._main(**kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/s3transfer/upload.py", line 758, in _main
client.put_object(Bucket=bucket, Key=key, Body=body, **extra_args)
File "/app/.heroku/python/lib/python3.10/site-packages/botocore/client.py", line 507, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/botocore/client.py", line 943, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.NoSuchBucket: An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist
! Error while running '$ python manage.py collectstatic --noinput'.
See traceback above for details.
You may need to update application code to resolve this error.
Or, you can disable collectstatic for this application:
$ heroku config:set DISABLE_COLLECTSTATIC=1
https://devcenter.heroku.com/articles/django-assets
! Push rejected, failed to compile Python app.
! Push failed
1条答案
按热度按时间7y4bm7vi1#
解决了我的问题。
在我例子中,我只是忘记了
AWS_STORAGE_BUCKET_NAME = ('AWS_STORAGE_BUCKET_NAME')
中的config
。应该是
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
。