当前位置:   article > 正文

Typora+python脚本实现OSS图片上传_python ossutil

python ossutil

Typora+python脚本实现OSS图片上传

Typora保存图片时会保存在本地,所以不方便;

有两种实现方式:

  • 1、PicGO软件+OSS对象存储
  • 2、Python+OSS对象存储

那么这里选择的是第二种方式;
第一种弊端:得一直运行PicGO这个软件很麻烦,那么当然从简

首先来到阿里云OSS查看自己的app_keyapp_secret注意保留下来;没有的自行创建key
在这里插入图片描述
现在来创建属于自己的存储节点信息,这里注意选择公共读

在这里插入图片描述创建成功后,来到概览保存一下我们的访问地址

在这里插入图片描述
到了这一步服务端OSS就设置OK了,现在本地需要拥有python环境以及PIP包依赖管理工具(下载包的玩意)
这里展示一下我的环境

在这里插入图片描述
启动开发工具复制以下代码,修改以下参数:

  • app_key // OSS中创建的Key
  • app_secret //OSS中生成的Secret
  • oss_url //这个地址上图所示的访问地址
  • bucket_name //节点名称
  • catalog //想要上传到服务器那个目录下,这个不需要自己手动创建,随便写
#! /usr/bin/python
# -*- coding: UTF-8 -*-
import logging
import uuid
import oss2
import os


class AliyunOSS:

    def __init__(self, app_key, app_secret, oss_url, bucket_name):
        auth = oss2.Auth(app_key, app_secret)
        self.bucket = oss2.Bucket(auth, oss_url, bucket_name)
        self.url_prefix = 'http://' + bucket_name+ '.' + oss_url
        logging.info('======= oss init ok')

    def make_unique_id(self):
        """
        生成唯一的id
        :return:
        """
        name = str(uuid.uuid4())
        name = uuid.uuid5(uuid.NAMESPACE_DNS, name)
        name = str(name)
        return name

    def upload_image_async(self, upload_dto, need_logging=False):
        """
        同步方式上传图片
        :param upload_dto: UploadFileDto 对象
        :return:
        """
        headers = {
            'Content-Type': upload_dto.content_type,
            'x-oss-meta-width': str(upload_dto.width),
            'x-oss-meta-height': str(upload_dto.height),
        }

        # 生成唯一的filename
        name = self.make_unique_id()

        result = self.bucket.put_object(name, upload_dto.file_data, headers=headers)
        if need_logging:
            logging.info('http status: {0}'.format(result.status))
            logging.info('request_id: {0}'.format(result.request_id))
            logging.info('ETag: {0}'.format(result.etag))
            logging.info('date: {0}'.format(result.headers['date']))

        return name, self.get_full_url(name)

    def get_image_meta(self, name):
        """
        返回 meta 信息. 不会全部返回阿里云的信息, 只会返回一部分
        :param name:
        :return:
        """
        oss_meta = self.bucket.head_object(name).headers

        meta = {
            'width': oss_meta['x-oss-meta-width'],
            'height': oss_meta['x-oss-meta-height'],
            'content_type': oss_meta['content-type']
        }
        return meta

    def upload_file_async(self, file_data, content_type, need_logging=False):
        """
        同步方式上传文件
        :param upload_dto: UploadFileDto 对象
        :return:
        """
        headers = {
            'Content-Type': content_type,
        }

        # 生成唯一的filename
        name = self.make_unique_id()

        result = self.bucket.put_object(name, file_data, headers=headers)
        if need_logging:
            logging.info('http status: {0}'.format(result.status))
            logging.info('request_id: {0}'.format(result.request_id))
            logging.info('ETag: {0}'.format(result.etag))
            logging.info('date: {0}'.format(result.headers['date']))

        return name, self.get_full_url(name)

    def get_full_url(self, name):
        """
        返回图片的网络路径
        :param name:
        :return:
        """
        return self.url_prefix + '/' + name

    def upload_local_file_sync(self,  file_path, content_type, need_logging=False):
        """
        同步方式上传文件
        """
        headers = {
            'Content-Type': content_type
        }
        # 生成唯一的filename
        file_ext = os.path.splitext(file_path)[1]
        name = catalog+self.make_unique_id() + file_ext.lower()


        # 必须以二进制的方式打开文件,因为需要知道文件包含的字节数。
        with open(file_path, 'rb') as fileobj:

            fileobj.seek(0)        # 0 表示从开始,直到文件结束。
            # Tell方法用于返回当前位置。
            current = fileobj.tell()
            result = self.bucket.put_object(name, fileobj, headers=headers)

        if need_logging:
            logging.info('http status: {0}'.format(result.status))
            logging.info('request_id: {0}'.format(result.request_id))
            logging.info('ETag: {0}'.format(result.etag))
            logging.info('date: {0}'.format(result.headers['date']))

        return name, self.get_full_url(name)


if __name__ == '__main__':

    import sys

    if len(sys.argv) < 2:
        print("调用错误, 图片格式不对")
        sys.exit(1)

    app_key = ''
    app_secret = ''
    oss_url = ''
    # 节点名称
    bucket_name = ''
    # 上传至md/目录
    catalog = 'md/'


    a_oss = AliyunOSS(app_key, app_secret, oss_url, bucket_name)

    # 返回值。
    url_list = []
    for i in range(1, len(sys.argv)):
        path = sys.argv[i]
        name, url = a_oss.upload_local_file_sync(path,  'image/png', True)
        url_list.append(url)

    print("Upload Success:")
    for url in url_list:
        print(url)


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155

那么再把Typora给设置一下就好了吧

依次点击文件——>偏好设置根据图上所示配置信息;
命令输入:python 脚本的绝对路径;如python D:\upload_oss.py

现在可以在编辑界面CTRL+V把图片粘贴上,自动上传到OSS中
如果出现BUG手动测试下脚本的可用性和自己本地的依赖包问题
命令如下:python D:\upload_oss.py D:\1.png
测试一下报错不,然后百度解决吧;环境正常就没问题了

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/773217
推荐阅读
相关标签
  

闽ICP备14008679号