2013-07-06 3 views
7

私は静的ファイルにdjango-storageとamazon s3を使用しています。ドキュメントの後、私は私のsettings.pyDjango-storageが変更された静的ファイルを検出しない

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バケットにアップロードされました。

はしかし、私は変更され、静的なファイルの名前を変更する場合は、静的ファイルは、しかし

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

を変更されたという事実にもかかわらず、出力された私の静的ファイルに変更を加えるとpython manage.py collectstaticこれを実行した後、変更静的ファイルが正しくあり私のs3バケツにコピーされました。

なぜ私は、変更された静的ファイルをdjango-storageがアップロードしないのですか?設定に問題があるのか​​、問題が深いのですか?

答えて

12

collectstaticは、 "target"ファイルがソースファイルより "若い"場合はファイルをスキップします。アマゾンS3のストレージのようなファイルが間違った日付を返すようです。

[code] [1]とデバッグサーバーの応答を調べることができます。たぶん、タイムゾーンに問題があります。

それとも、ただのreadme.txtから

+0

ありがとう:この行で特定の設定で

TIME_ZONE = 'UTC' 

実行collectstatic。私は誰もが私の問題に正確な解決策を投稿するかどうかを確認するのを待つつもりですが、もしあなたが+50を持つことができない場合: – bab

+0

--clearは私のためにs3で動作していないようです。私が手動でs3からファイルを削除すると、それらはすべて再コピーされます。 – mgojohn

5

https://github.com/antonagestam/collectfast

を収集する前にすべてのファイルをS3に削除されるようにcollectstaticする--clear引数を渡すことができますから、MD5サムとのETagを比較して、カスタム管理コマンドS3と2つが同じスキップファイルコピーである場合。これによりタイムスタンプを更新するソース管理システムとしてgitを使用している場合、静的な収集をより高速に実行します。

0

この質問は少し古いですが、将来誰かを助ける場合は、私は自分の経験を分かち合うと考えました。私が確認したことは、他のスレッドで見つかったアドバイスに続いて、これは確かにタイムゾーンの違いによるものです。私のdjango時間は間違っていませんでしたが、ESTに設定され、S3はGMTに設定されました。テストでは、私はdjango-storage 1.1.5に戻った。これはcollectstaticな作業をするようだった。部分的には個人的な好みのため、私はdjango-storageの3つのバージョンをロールバックしてバグ修正を失うことや、b)プロジェクトのコンポーネントのタイムゾーンを変更することを嫌っていました。 1)。

私は前述の変更なしで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() 
2

ちょうどこの設定でcollectstaticの同期のために、設定ファイルを作成します。これは働いていた

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

これが私の問題を解決しました。 – kmomo

関連する問題