blog-img-manager/sync.py

59 lines
2.3 KiB
Python
Raw Normal View History

2024-04-20 02:14:37 +00:00
import os, uuid
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
2024-04-24 03:01:26 +00:00
import argparse
2024-04-27 07:29:59 +00:00
import json
2024-04-29 06:09:13 +00:00
2024-04-27 07:29:59 +00:00
defaults=json.load(open('defaults.json'))
2024-04-29 06:09:13 +00:00
2024-04-24 03:01:26 +00:00
parser = argparse.ArgumentParser()
2024-04-27 07:29:59 +00:00
parser.add_argument('--container', help='Name of the container', default=defaults['container'])
parser.add_argument('--remote', help='Path to the remote images', default=defaults['remote'])
parser.add_argument('--local', help='Path to the local images', default=defaults['local'])
parser.add_argument('--ignore', help='Files to ignore', default=defaults['ignore'], action='append')
2024-04-24 03:16:46 +00:00
parser.add_argument('--overwrite', help='Overwrite existing images', action='store_true')
2024-04-24 03:01:26 +00:00
args=parser.parse_args()
2024-04-20 02:14:37 +00:00
2024-04-29 06:09:13 +00:00
pics=[]
2024-04-27 07:29:59 +00:00
if args.remote!='' and args.remote[-1] != '/':
2024-04-24 03:01:26 +00:00
args.remote += '/'
2024-04-20 02:14:37 +00:00
try:
with open('secret.txt', 'r') as f:
connect_str = f.read()
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
2024-04-24 03:01:26 +00:00
container_client = blob_service_client.get_container_client(args.container)
existing_files=[blob.name.split("/")[-1] for blob in container_client.list_blobs(name_starts_with=args.remote)]
2024-04-24 03:16:46 +00:00
2024-04-24 03:01:26 +00:00
for root,fir,files in os.walk(args.local):
2024-04-20 02:14:37 +00:00
for file in files:
2024-04-29 06:09:13 +00:00
pics.append(file)
2024-04-24 03:16:46 +00:00
if file in args.ignore:
print("ignored: " + file)
2024-04-20 02:14:37 +00:00
continue
2024-04-24 03:16:46 +00:00
if file in existing_files:
if args.overwrite:
print("Overwriting: " + file)
blob_client = blob_service_client.get_blob_client(container=args.container, blob=args.remote+file)
blob_client.delete_blob()
else:
print("skipped: " + file)
continue
2024-04-20 02:14:37 +00:00
try:
print("Uploading: " + file)
img_path = os.path.join(root,file)
2024-04-24 03:01:26 +00:00
blob_client = blob_service_client.get_blob_client(container=args.container, blob=args.remote+file)
2024-04-20 02:14:37 +00:00
with open(file=img_path, mode="rb") as data:
blob_client.upload_blob(data)
except Exception as ex:
print(f"Error uploading {file}.")
print(ex)
print("Upload finished.")
except Exception as ex:
print('Exception:')
2024-04-29 06:09:13 +00:00
print(ex)
finally:
json.dump(pics, open('pics.json', 'w'))