Added dropbox api support as service and cleaned up get single call
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
import requests
|
||||
from django.conf import settings
|
||||
import dropbox
|
||||
|
||||
|
||||
class DropboxService:
|
||||
|
||||
@staticmethod
|
||||
def create_file(filename: str, file: bytes) -> bool:
|
||||
"""Create / save (or overwrite) an file on the dropbox storage.
|
||||
|
||||
:param filename: filename
|
||||
:param file: bytes representation of the file
|
||||
:return: Whether file was successfully uploaded
|
||||
"""
|
||||
try:
|
||||
dbx = dropbox.Dropbox(settings.DROPBOX_OAUTH2_ACCESS_TOKEN)
|
||||
dbx.files_upload(file, settings.DROPBOX_IMAGE_FOLDER + filename)
|
||||
except:
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def read_file(filename: str) -> bytes:
|
||||
"""Read file on the dropbox storage.
|
||||
|
||||
:param filename: filename
|
||||
:return: bytes representation of the file or None on error
|
||||
"""
|
||||
file_bytes: bytes
|
||||
try:
|
||||
dbx = dropbox.Dropbox(settings.DROPBOX_OAUTH2_ACCESS_TOKEN)
|
||||
f: requests.models.Response
|
||||
metadata, f = dbx.files_download(settings.DROPBOX_IMAGE_FOLDER + filename)
|
||||
file_bytes = f.content
|
||||
if f is not None:
|
||||
f.close()
|
||||
except:
|
||||
print("Error downloading file from dropbox")
|
||||
return file_bytes
|
||||
|
||||
@staticmethod
|
||||
def update_file(filename: str, file: bytes) -> bool:
|
||||
"""Update (currently: overwrite) an file on the dropbox storage.
|
||||
|
||||
:param filename: filename of the file
|
||||
:param file: bytes representation of the file
|
||||
:return: Whether file was successfully uploaded
|
||||
"""
|
||||
return DropboxService.create_file(filename, file)
|
||||
|
||||
@staticmethod
|
||||
def delete_file(filename: str) -> bool:
|
||||
"""Delete an file from the dropbox storage.
|
||||
|
||||
:param filename: filename of the file
|
||||
:return: Whether file was successfully deleted
|
||||
"""
|
||||
try:
|
||||
dbx = dropbox.Dropbox(settings.DROPBOX_OAUTH2_ACCESS_TOKEN)
|
||||
dbx.files_delete_v2(settings.DROPBOX_IMAGE_FOLDER + filename)
|
||||
except:
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,13 @@
|
||||
import base64
|
||||
|
||||
|
||||
class WrapperService:
|
||||
|
||||
@staticmethod
|
||||
def wrap_file(file_bytes: bytes) -> str:
|
||||
file_encoded_b64 = base64.b64encode(file_bytes)
|
||||
return file_encoded_b64.decode('utf-8')
|
||||
|
||||
@staticmethod
|
||||
def unwrap_file(file_str: str) -> bytes:
|
||||
return base64.b64decode(file_str)
|
||||
Reference in New Issue
Block a user