Skip to content

Instantly share code, notes, and snippets.

@wzyboy
Last active December 15, 2017 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wzyboy/7702fa6d2cc0d15a98a013f74b6f280b to your computer and use it in GitHub Desktop.
Save wzyboy/7702fa6d2cc0d15a98a013f74b6f280b to your computer and use it in GitHub Desktop.
Attaching images in Lektor
#!/usr/bin/env python
import os
import argparse
import mimetypes
from datetime import datetime
from urllib.parse import quote
import boto3
DEFAULT_S3_BUCKET = 'wzyboy-wordpress-uploads'
def main():
ap = argparse.ArgumentParser()
ap.add_argument('file_path')
ap.add_argument('--bucket', default=DEFAULT_S3_BUCKET)
args = ap.parse_args()
# Compute S3 key
_mtime = os.path.getmtime(args.file_path)
mtime = datetime.fromtimestamp(_mtime)
month_dir = mtime.strftime('%Y-%m')
basename = os.path.basename(args.file_path)
s3_key = f'{month_dir}/{basename}'
s3_bucket = args.bucket
# Get Content-Type
content_type = mimetypes.guess_type(args.file_path)[0]
if content_type is None:
content_type = 'binary/octet-stream' # default AWS Content-Type
print(f'Content-Type: {content_type}')
# Upload
print(f'Uploading to: s3://{s3_bucket}/{s3_key}')
s3 = boto3.client('s3')
s3.upload_file(
args.file_path, s3_bucket, s3_key,
ExtraArgs={
'ContentType': content_type,
'Metadata': {
'mtime': str(_mtime) # follow rclone's convention
}
}
)
url = f'https://s3.amazonaws.com/{s3_bucket}/{quote(s3_key)}'
img_alt = os.path.splitext(basename)[0]
img_tag = f'<img alt="{img_alt}" class="img-responsive" src="{url}"/>'
img_tag_with_a = f'<a href="{url}">{img_tag}</a>'
print(url)
print(img_tag)
print(img_tag_with_a)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment