0
現在、Pythonを使用して2つのファイルをダウンロードしようとしています(gzippedファイルともう1つはチェックサムです)。gzipファイルをダウンロードしてmd5チェックサムし、一致する場合は抽出データを保存します。
gzippedファイルの内容がmd5チェックサムと一致することを確認してから、その内容をターゲットディレクトリに保存したいと考えています。
ファイルhereのダウンロード方法を知り、チェックサムhereの計算方法を学びました。私はJSON設定ファイルからURLを読み込み、JSONファイルの値を解析する方法を学びましたhere。
次のスクリプトにまとめてありますが、gzippedファイルの検証済みの内容を保存しようとしています。あなたのmd5Gzip
で
import json
import gzip
import urllib
import hashlib
# Function for creating an md5 checksum of a file
def md5Gzip(fname):
hash_md5 = hashlib.md5()
with gzip.open(fname, 'rb') as f:
# Make an iterable of the file and divide into 4096 byte chunks
# The iteration ends when we hit an empty byte string (b"")
for chunk in iter(lambda: f.read(4096), b""):
# Update the MD5 hash with the chunk
hash_md5.update(chunk)
return hash_md5.hexdigest()
# Open the configuration file in the current directory
with open('./config.json') as configFile:
data = json.load(configFile)
# Open the downloaded checksum file
with open(urllib.urlretrieve(data['checksumUrl'])[0]) as checksumFile:
md5Checksum = checksumFile.read()
# Open the downloaded db file and get it's md5 checksum via gzip.open
fileMd5 = md5Gzip(urllib.urlretrieve(data['fileUrl'])[0])
if (fileMd5 == md5Checksum):
print 'Downloaded Correct File'
# save correct file
else:
print 'Downloaded Incorrect File'
# do some error handling
、単にハッシュの代わりに' tuple'を返します。すなわち、return hash_md5.digest()、file_content' –