繁体   English   中英

Django存储没有检测到更改的静态文件

[英]Django-storages not detecting changed static files

我正在使用django-storages和amazon s3作为我的静态文件。 在文档之后,我将这些设置放在我的settings.py中

STATIC_URL = 'https://mybucket.s3.amazonaws.com/'

ADMIN_MEDIA_PREFIX = 'https://mybucket.s3.amazonaws.com/admin/'

INSTALLED_APPS += (
    'storages',
)

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = 'mybucket_key_id'
AWS_SECRET_ACCESS_KEY = 'mybucket_access_key'
AWS_STORAGE_BUCKET_NAME = 'mybucket'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

我第一次运行收集静态一切正常,我的静态文件上传到我的s3桶。

但是,在对我的静态文件进行更改并运行python manage.py collectstatic尽管静态文件已被修改,但python manage.py collectstatic输出

-----> Collecting static files
    0 static files copied, 81 unmodified.

但是,如果我重命名更改的静态文件,更改的静态文件将正确复制到我的s3存储桶。

为什么django-storage上传我更改的静态文件? 是配置问题还是问题更严重?

如果“目标”文件比源文件“更年轻”,则collectstatic会跳过文件。 似乎亚马逊S3存储返回错误的日期为您的文件。

你可以调查[code] [1]并调试服务器响应。 也许时区存在问题。

或者您可以将--clear参数传递给collectstatic,以便在收集之前在S3上删除所有文件

https://github.com/antonagestam/collectfast

来自readme.txt:自定义管理命令,用于比较来自S3的MD5总和和etag以及两者是否相同的跳过文件副本。 如果您使用git作为更新时间戳的源控制系统,这使得运行collect static MUCH更快。

使用此配置创建仅用于collectstatic同步的设置文件:

TIME_ZONE = 'UTC'

使用以下行运行具有特定设置的collectstatic:

python manage.py collectstatic --settings=settings.collectstatic

这个问题有点旧,但如果将来有人帮助,我想我会分享我的经验。 根据其他主题中的建议我确认,对我来说,这确实是由时区差异造成的。 我的django时间不正确,但设置为EST,S3设置为GMT。 在测试中,我恢复了django-storages 1.1.5,它确实似乎得到了收集静态工作。 部分由于个人偏好,我不愿意a)回滚三个版本的django-storage并丢失任何潜在的错误修复或b)改变我项目组件的时区,这基本上归结为一个便利功能(尽管很重要)一)。

我写了一个简短的脚本来完成与collectstatic相同的工作而没有上述改动。 它需要对您的应用进行一些修改,但如果它放在应用程序级别并且'static_dirs'替换为项目应用程序的名称,则应该适用于标准情况。 它通过终端运行'python whatever_you_call_it.py -e environment_name(将其设置为你的aws存储桶)。

import sys, os, subprocess
import boto3
import botocore
from boto3.session import Session
import argparse
import os.path, time
from datetime import datetime, timedelta
import pytz

utc = pytz.UTC
DEV_BUCKET_NAME = 'dev-homfield-media-root'
PROD_BUCKET_NAME = 'homfield-media-root'
static_dirs = ['accounts', 'messaging', 'payments', 'search', 'sitewide']

def main():
    try: 
        parser = argparse.ArgumentParser(description='Homfield Collectstatic. Our version of collectstatic to fix django-storages bug.\n')
        parser.add_argument('-e', '--environment', type=str, required=True, help='Name of environment (dev/prod)')
        args = parser.parse_args()
        vargs = vars(args)
        if vargs['environment'] == 'dev':
            selected_bucket = DEV_BUCKET_NAME
            print "\nAre you sure? You're about to push to the DEV bucket. (Y/n)"
        elif vargs['environment'] == 'prod':
            selected_bucket = PROD_BUCKET_NAME
            print "Are you sure? You're about to push to the PROD bucket. (Y/n)"
        else:
            raise ValueError

        acceptable = ['Y', 'y', 'N', 'n']
        confirmation = raw_input().strip()
        while confirmation not in acceptable:
            print "That's an invalid response. (Y/n)"
            confirmation = raw_input().strip()

        if confirmation == 'Y' or confirmation == 'y':
            run(selected_bucket)
        else:
            print "Collectstatic aborted."
    except Exception as e:
        print type(e)
        print "An error occured. S3 staticfiles may not have been updated."


def run(bucket_name):

    #open session with S3
    session = Session(aws_access_key_id='{aws_access_key_id}',
        aws_secret_access_key='{aws_secret_access_key}',
        region_name='us-east-1')
    s3 = session.resource('s3')
    bucket = s3.Bucket(bucket_name)

    # loop through static directories
    for directory in static_dirs:
        rootDir = './' + directory + "/static"
        print('Checking directory: %s' % rootDir)

        #loop through subdirectories
        for dirName, subdirList, fileList in os.walk(rootDir):
            #loop through all files in subdirectory
            for fname in fileList:
                try:
                    if fname == '.DS_Store':
                        continue

                    # find and qualify file last modified time
                    full_path = dirName + "/" + fname
                    last_mod_string = time.ctime(os.path.getmtime(full_path))
                    file_last_mod = datetime.strptime(last_mod_string, "%a %b %d %H:%M:%S %Y") + timedelta(hours=5)
                    file_last_mod = utc.localize(file_last_mod)

                    # truncate path for S3 loop and find object, delete and update if it has been updates
                    s3_path = full_path[full_path.find('static'):]
                    found = False
                    for key in bucket.objects.all():
                        if key.key == s3_path:
                            found = True 
                            last_mode_date = key.last_modified
                            if last_mode_date < file_last_mod:
                                key.delete()
                                s3.Object(bucket_name, s3_path).put(Body=open(full_path, 'r'), ContentType=get_mime_type(full_path))
                                print "\tUpdated : " + full_path
                    if not found:
                        # if file not found in S3 it is new, send it up
                        print "\tFound a new file. Uploading : " + full_path
                        s3.Object(bucket_name, s3_path).put(Body=open(full_path, 'r'), ContentType=get_mime_type(full_path))
                except:
                    print "ALERT: Big time problems with: " + full_path + ". I'm bowin' out dawg, this shitz on u." 


def get_mime_type(full_path):
    try:
        last_index = full_path.rfind('.')
        if last_index < 0:
            return 'application/octet-stream'
        extension = full_path[last_index:]
        return {
            '.js' : 'application/javascript',
            '.css' : 'text/css',
            '.txt' : 'text/plain',
            '.png' : 'image/png',
            '.jpg' : 'image/jpeg',
            '.jpeg' : 'image/jpeg',
            '.eot' : 'application/vnd.ms-fontobject',
            '.svg' : 'image/svg+xml',
            '.ttf' : 'application/octet-stream',
            '.woff' : 'application/x-font-woff',
            '.woff2' : 'application/octet-stream'
        }[extension]
    except:
        'ALERT: Couldn\'t match mime type for '+ full_path + '. Sending to S3 as application/octet-stream.'

if __name__ == '__main__':
    main()

暂无
暂无

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

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