import os import hashlib import mimetypes from django.core.files.storage import default_storage from pingcap_sso.file_storage import pingcap_cdn_storage from pingcap_sso.models import Upload def upload_file(file_obj, user, is_private=True): assert file_obj, 'file_obj can not be empty' content_hash = hashlib.sha1(file_obj.read()).hexdigest() content_type, _ = mimetypes.guess_type(file_obj.name, strict=False) file_path = generate_filepath_by_hash(content_hash) _, file_extension = os.path.splitext(file_obj.name) if file_extension: file_path += file_extension file_obj.seek(0) file_path = default_storage.save(file_path, file_obj) if hasattr(file_obj, 'image'): image_width = file_obj.image.width image_height = file_obj.image.height else: image_width = image_height = None return Upload.objects.create( user=user, original_filename=file_obj.name, filesize=file_obj.size, width=image_width, height=image_height, path=file_path, sha1=content_hash, extension=content_type, is_private=is_private ) def upload_file_to_cdn(file_obj): assert file_obj, 'file_obj can not be empty' content_hash = hashlib.sha256(file_obj.read()).hexdigest() content_type, _ = mimetypes.guess_type(file_obj.name, strict=False) file_path = generate_filepath_by_hash(content_hash) _, file_extension = os.path.splitext(file_obj.name) if file_extension: file_path += file_extension file_obj.seek(0) file_path = pingcap_cdn_storage.save(file_path, file_obj) return file_path, pingcap_cdn_storage.url(file_path) def generate_filepath_by_hash(file_hash): return '{}/{}/{}'.format( file_hash[0], file_hash[1], file_hash )