epub converter: refactor Access class

This commit is contained in:
shirshasa
2021-08-17 18:34:27 +03:00
parent db8bca336c
commit 4fb3aee2b0
3 changed files with 7 additions and 27 deletions

View File

@@ -3,6 +3,7 @@ import os
import time import time
import requests import requests
from threading import Event from threading import Event
from io import BytesIO
class Access: class Access:
@@ -111,39 +112,18 @@ class Access:
return content return content
def send_image(self, img, doc_id): def send_image(self, img_path, doc_id, img_content: bytes = None):
if self.is_time_for_refreshing():
self.refresh_token()
self.refreshing.wait()
with open(img, 'rb') as img_file:
files = {
'image': (os.path.basename(img), img_file)
}
response = requests.post(f'{self.url}/doc-convert/image', files=files, headers=self.headers)
if response.status_code == 400:
self.update_status(doc_id, self.ERROR)
raise Exception(f'400 Bad request: {response.json()["message"]}.')
elif response.status_code == 200:
img_url = response.json()['imageUrl']
else:
self.update_status(doc_id, self.ERROR)
raise Exception(f'{response.status_code}')
return img_url
def send_image_by_bytes(self, img_file_path, img_content: bytes, doc_id):
if self.is_time_for_refreshing(): if self.is_time_for_refreshing():
self.refresh_token() self.refresh_token()
self.refreshing.wait() self.refreshing.wait()
img_obj = BytesIO(img_content) if img_content else open(img_path, 'rb')
files = { files = {
'image': (os.path.basename(img_file_path), img_content) 'image': (os.path.basename(img_path), img_obj)
} }
response = requests.post(f'{self.url}/doc-convert/image', files=files, headers=self.headers) response = requests.post(f'{self.url}/doc-convert/image', files=files, headers=self.headers)
img_obj.close()
if response.status_code == 400: if response.status_code == 400:
self.update_status(doc_id, self.ERROR) self.update_status(doc_id, self.ERROR)

View File

@@ -23,7 +23,7 @@ def save_image_locally(img_file_path, img_content, book_id):
def save_image_to_aws(access: Access, img_file_path, img_content: bytes, book_id): def save_image_to_aws(access: Access, img_file_path, img_content: bytes, book_id):
link = access.send_image_by_bytes(img_file_path, img_content, book_id) link = access.send_image(img_file_path, doc_id=book_id, img_content=img_content)
return link return link

View File

@@ -380,7 +380,7 @@ class HTMLPreprocessor:
img_path = pathlib.Path(f'{html_path.parent}', f'{img_name}') img_path = pathlib.Path(f'{html_path.parent}', f'{img_name}')
if access is not None: if access is not None:
link = access.send_image(img_path, book_id) link = access.send_image(img_path, doc_id=book_id)
img.attrs['src'] = link img.attrs['src'] = link
self.logger_object.log(f'{img_name} successfully uploaded.') self.logger_object.log(f'{img_name} successfully uploaded.')
else: else: