Django mdeditor integrates Tencent COS to upload pictures to Tencent cloud

The object Storage of large factories provides complete SDK, which is very simple to use. There are two scenarios for django to use object Storage. One is combined with django's Storage class. Pictures are uploaded to COS through the model, and then deleted by django. They are not retained locally; Another custom scenario, for example, is used in conjunction with django mdeditor. This article introduces the second one, which is directly uploaded to Tencent COS through "adding pictures" in combination with django mdeditor editor editor.

Tencent COSpython document address:
The usage of Tencent COS in django scenario will be studied for some time in the future. Tencent cos provides many interfaces such as object upload, download, viewing object list, initializing client, creating bucket, viewing bucket list, etc. This paper focuses on object upload.

Key points for consolidation
Understand the workflow of Django mdeditor
Django mdeditor uploads images locally by default. After selecting the image, the upload will be completed and the relative path will be returned to the editor. The editor and the back-end communicate using json. The js file for the editor is site packages / mdeditor / static / mdeditor / js / plugins / image dialog / image dialog js, python file is site packages / mdeditor / views py. The approximate process is:

1. Render picture upload form

The form consists of image dialog JS rendering, the value of action is / mdeditor/uploads/?guid=1639898526591. guid is the time stamp during rendering. It's not clear what it is used for. You can't see the use of this parameter in the view.

2. Editor URLs py

All requests related to uploads are submitted to this route and views. Com is called The UploadView in. Py receives the picture, saves it, and returns the path to the editor

3, UploadView

class UploadView(generic.View):  
    """ upload image file """  

    def dispatch(self, *args, **kwargs):  
        return super(UploadView, self).dispatch(*args, **kwargs)  

    def post(self, request, *args, **kwargs):  
        upload_image = request.FILES.get("editormd-image-file", None)  
        print('upload: ', upload_image)  
        media_root = settings.MEDIA_ROOT  

        # image none check  
        if not upload_image:  
            return JsonResponse({  
                'success': 0,  
                'message': "The picture to be uploaded was not obtained",  
                'url': ""  

        # image format check  
        file_name_list ='.')  
        file_extension = file_name_list.pop(-1)  
        file_name = '.'.join(file_name_list)  
        if file_extension not in MDEDITOR_CONFIGS['upload_image_formats']:  
            return JsonResponse({  
                'success': 0,  
                'message': "The format of uploaded picture is wrong. The format of uploaded picture is:%s" % ','.join(  
                'url': ""  

        # image floder check  
        file_path = os.path.join(media_root, MDEDITOR_CONFIGS['image_folder'])  
        print('Upload path:', file_path)  
        if not os.path.exists(file_path):  
            except Exception as err:  
                return JsonResponse({  
                    'success': 0,  
                    'message': "Upload failed:%s" % str(err),  
                    'url': ""  

        # save image  
        file_full_name = '%s_%s.%s' % (file_name,  
        with open(os.path.join(file_path, file_full_name), 'wb+') as file:  
            for chunk in upload_image.chunks():  

        return JsonResponse({'success': 1,  
                             'message': "Upload succeeded!",  
                             'url': os.path.join(settings.MEDIA_URL,  

The editor part is relatively easy to understand, but it's a little troublesome to modify the content of the editor interface. You can customize the toolbar through settings, but it's a little difficult to adjust others, because the author encapsulates it so well that he can't understand js files at all.

Understand the interface and usage of Tencent COS
Tencent COS documents are complete. You can read them carefully and practice them. The COS workflow is as follows: Download SDK, initialize COS client = > configure Tencent ID, password and bucket id = > select file = > carry necessary parameters (such as the name and suffix of the uploaded image, which are controlled by the parameter key) = > read the url of the image. The whole process document has detailed sample code.

Integrated thinking
Imitate the UploadView of the editor, write a new view, and upload the part of saving the picture locally to Tencent COS.

Implementation code
Write a COS class in the view of the editor
This class implements client initialization, upload and read url. However, in order to standardize the point, first configure the basic information of COS in the setting file.

    'secret_id': 'Tencent cloud id',  
    'secret_key': 'Key of Tencent cloud',  
    'bucket': 'Storage bucket id',  
    'region': 'Bucket area',  

The above information needs to be found in Tencent cloud.
COS class is written in the editor class:

class TencentCOS:  

    def __init__(self):  
        self.secret_id = settings.TENCENT_COS['secret_id']  
        self.secret_key = settings.TENCENT_COS['secret_key']  
        self.bucket = settings.TENCENT_COS['bucket']  
        self.region = settings.TENCENT_COS['region']  
        self.token = None  
        self.scheme = 'https'  

    #Initialize client  
    def client(self):  
        logging.basicConfig(level=logging.INFO, stream=sys.stdout)  
        config = CosConfig(  
        return CosS3Client(config) #Returns an initialized client. Subsequent operations need to be based on this client instance  

    # Get object url  
    def get_obj_url(self, bucket, key):  
        return self.client().get_object_url(bucket, key)  

    #Upload the file and return the uploaded url  
    def upload_cos(self, image, key):  
        with open(image, 'rb') as fp:  
            response = self.client().put_object(  
                Bucket = self.bucket,  
                Body = fp,  
                Key = key,   #key is the name saved in cos  
                StorageClass = 'STANDARD',  
                EnableMD5 = False  
        return self.get_obj_url(self.bucket, key)  

1. In upload_ In the cos method, the parameter image is the path to upload the picture, and the absolute path is used for uploading. The parameter key is the name saved after uploading to Cos. The file name + suffix is required. The local picture name may be Chinese. You need to reorganize the key yourself, which is equal to renaming the picture, and then pass the parameter to upload_cos, cos will use the key to save the image.

2,get_ obj_ The url method is used to obtain the url of the uploaded picture. Some netizens organize the url according to the link law of COS, which is also possible.

  • Implement a view by yourself

The second half of the code, you can browse my personal blog

Keywords: Python Django

Added by iluv8250 on Mon, 20 Dec 2021 12:50:43 +0200