18

サーバーのコピーがローカルのコピーよりも新しい場合にのみ、サーバーから新しいファイルをダウンロードする標準的なpythonicの方法は何ですか?

今日の私の python-search-fu は非常に弱いか、以下のように独自の日時パーサーと比較機能をロールバックする必要があります。本当にないのrequests.header.get_datetime_object('last-modified')?またはrequest.save_to_file(url, outfile, maintain_datetime=True)

import requests
import datetime

r = requests.head(url)
url_time = r.headers['last-modified']
file_time = datetime.datetime.fromtimestamp(os.path.getmtime(dstFile))
print url_time  #emits 'Sat, 28 Mar 2015 08:05:42 GMT' on my machine
print file_time #emits '2015-03-27 21:53:28.175072' 

if time_is_older(url_time, file_time):
    print 'url modtime is not newer than local file, skipping download'
    return
else:
    do_download(url)
    os.utime(dstFile, url_time) # maintain server's file timestamp

def time_is_older(str_time, time_object):
    ''' Parse str_time and see if is older than time_object.
        This is a fragile function, what if str_time is in different locale?
    '''
    parsed_time = datetime.datetime.strptime(str_time, 
        #Fri, 27 Mar 2015 08:05:42 GMT
        '%a, %d %b %Y %X %Z')
    return parsed_time < time_object
4

2 に答える 2