mirror of https://github.com/veops/cmdb.git
feat(api): add get_file_binary_str and save (#329)
This commit is contained in:
parent
1ee8ed7c4f
commit
7b8e120974
|
@ -1,3 +1,4 @@
|
||||||
|
import base64
|
||||||
import uuid
|
import uuid
|
||||||
import os
|
import os
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
@ -29,14 +30,14 @@ class CommonFileCRUD:
|
||||||
return CommonFile.create(**kwargs)
|
return CommonFile.create(**kwargs)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_file(file_name):
|
def get_file(file_name, to_str=False):
|
||||||
existed = CommonFile.get_by(file_name=file_name, first=True, to_dict=False)
|
existed = CommonFile.get_by(file_name=file_name, first=True, to_dict=False)
|
||||||
if not existed:
|
if not existed:
|
||||||
abort(400, ErrFormat.file_not_found)
|
abort(400, ErrFormat.file_not_found)
|
||||||
|
|
||||||
uncompressed_data = lz4.frame.decompress(existed.binary)
|
uncompressed_data = lz4.frame.decompress(existed.binary)
|
||||||
|
|
||||||
return BytesIO(uncompressed_data)
|
return base64.b64encode(uncompressed_data).decode('utf-8') if to_str else BytesIO(uncompressed_data)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def sync_file_to_db():
|
def sync_file_to_db():
|
||||||
|
@ -66,3 +67,28 @@ class CommonFileCRUD:
|
||||||
current_app.logger.info(f'sync file {file} to db')
|
current_app.logger.info(f'sync file {file} to db')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
current_app.logger.error(f'sync file {file} to db error: {e}')
|
current_app.logger.error(f'sync file {file} to db error: {e}')
|
||||||
|
|
||||||
|
def get_file_binary_str(self, file_name):
|
||||||
|
return self.get_file(file_name, True)
|
||||||
|
|
||||||
|
def save_str_to_file(self, file_name, str_data):
|
||||||
|
try:
|
||||||
|
self.get_file(file_name)
|
||||||
|
current_app.logger.info(f'file {file_name} already exists')
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
# file not found
|
||||||
|
pass
|
||||||
|
|
||||||
|
bytes_data = base64.b64decode(str_data)
|
||||||
|
compressed_data = lz4.frame.compress(bytes_data)
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.add_file(
|
||||||
|
origin_name=file_name,
|
||||||
|
file_name=file_name,
|
||||||
|
binary=compressed_data
|
||||||
|
)
|
||||||
|
current_app.logger.info(f'save_str_to_file {file_name} success')
|
||||||
|
except Exception as e:
|
||||||
|
current_app.logger.error(f"save_str_to_file error: {e}")
|
||||||
|
|
Loading…
Reference in New Issue