Store document image uploads in SQLite
This commit is contained in:
@@ -45,14 +45,15 @@ def read_token(filename):
|
||||
return value
|
||||
|
||||
|
||||
def request(base, token, method, path, payload=None, request_id=None):
|
||||
data = None if payload is None else json.dumps(payload, ensure_ascii=False).encode()
|
||||
def request(base, token, method, path, payload=None, request_id=None, *, image_type=None):
|
||||
data = payload if image_type else (None if payload is None else json.dumps(payload, ensure_ascii=False).encode())
|
||||
if data is not None and len(data) > 8 * 1024 * 1024:
|
||||
raise ValueError('Request exceeds 8 MiB; split into smaller atomic batches')
|
||||
headers = {'Authorization': 'Bearer ' + token, 'Accept': 'application/json'}
|
||||
if data is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
headers['Idempotency-Key'] = request_id
|
||||
headers['Content-Type'] = image_type or 'application/json'
|
||||
if request_id is not None:
|
||||
headers['Idempotency-Key'] = request_id
|
||||
opener = urllib.request.build_opener(NoRedirect())
|
||||
for attempt in range(2):
|
||||
req = urllib.request.Request(base + path, data=data, method=method, headers=headers)
|
||||
@@ -127,6 +128,8 @@ def main():
|
||||
editing.add_argument('slug')
|
||||
editing.add_argument('file')
|
||||
editing.add_argument('--request-id')
|
||||
upload = sub.add_parser('upload-image', help='Upload a static image and print its Markdown URL')
|
||||
upload.add_argument('file')
|
||||
saving = sub.add_parser('save')
|
||||
saving.add_argument('file', help='Private JSON file or - for stdin; one document or {documents: [...]}')
|
||||
saving.add_argument('--request-id', help='Reuse this id only with the same input when retrying')
|
||||
@@ -136,7 +139,18 @@ def main():
|
||||
try:
|
||||
base = server_url(args.url)
|
||||
token = read_token(args.key_file)
|
||||
if args.command == 'list':
|
||||
if args.command == 'upload-image':
|
||||
image = Path(args.file)
|
||||
image_types = {'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp'}
|
||||
image_type = image_types.get(image.suffix.lower())
|
||||
if not image_type:
|
||||
raise ValueError('Use a PNG, JPEG or WebP image')
|
||||
with image.open('rb') as source:
|
||||
data = source.read(8 * 1024 * 1024 + 1)
|
||||
if len(data) > 8 * 1024 * 1024:
|
||||
raise ValueError('Image exceeds 8 MiB')
|
||||
result = request(base, token, 'POST', '/api/documents/images', data, image_type=image_type)
|
||||
elif args.command == 'list':
|
||||
result = request(base, token, 'GET', '/api/documents?' + urllib.parse.urlencode(
|
||||
{'limit': args.limit, 'offset': args.offset}))
|
||||
elif args.command == 'get':
|
||||
|
||||
Reference in New Issue
Block a user