分享一个自己抄抄改改的Python七牛图床脚本
习惯用 markdown 写博客了, 差个好用的图床, 于是抄抄改改弄了个凑合用的脚本, 自用貌似还是挺方便的, 分享给各位.
workflow: 运行脚本 --> 截图到指定监控目录 --> 粘贴图片链接到 markdown 正文 :)
效果图:

分享一个自己抄抄改改的Python七牛图床脚本
3 回复
看到你分享的七牛图床脚本,挺有意思的。我也经常用七牛云存图片,自己写了个脚本处理日常需求。下面是我常用的版本,加了点错误处理和进度显示:
import os
import sys
from qiniu import Auth, put_file, etag
from qiniu import BucketManager
import mimetypes
class QiniuUploader:
def __init__(self, access_key, secret_key, bucket_name, domain):
self.auth = Auth(access_key, secret_key)
self.bucket_name = bucket_name
self.domain = domain.rstrip('/')
self.bucket_manager = BucketManager(self.auth)
def upload_file(self, file_path, key=None):
"""上传单个文件"""
if not os.path.exists(file_path):
print(f"文件不存在: {file_path}")
return None
if key is None:
key = os.path.basename(file_path)
# 获取文件MIME类型
mime_type, _ = mimetypes.guess_type(file_path)
if mime_type is None:
mime_type = 'application/octet-stream'
# 生成上传Token
token = self.auth.upload_token(self.bucket_name, key, 3600)
try:
ret, info = put_file(token, key, file_path, mime_type=mime_type)
if info.status_code == 200:
url = f"{self.domain}/{key}"
print(f"上传成功: {url}")
return url
else:
print(f"上传失败: {info}")
return None
except Exception as e:
print(f"上传异常: {e}")
return None
def upload_directory(self, dir_path, prefix=''):
"""上传目录下的所有文件"""
if not os.path.isdir(dir_path):
print(f"目录不存在: {dir_path}")
return []
uploaded_urls = []
files = [f for f in os.listdir(dir_path)
if os.path.isfile(os.path.join(dir_path, f))]
total = len(files)
for i, filename in enumerate(files, 1):
file_path = os.path.join(dir_path, filename)
if prefix:
key = f"{prefix}/{filename}"
else:
key = filename
print(f"[{i}/{total}] 正在上传: {filename}")
url = self.upload_file(file_path, key)
if url:
uploaded_urls.append(url)
return uploaded_urls
def list_files(self, prefix='', limit=100):
"""列出存储空间中的文件"""
ret, eof, info = self.bucket_manager.list(
self.bucket_name, prefix=prefix, limit=limit
)
if info.status_code == 200:
items = ret.get('items', [])
for item in items:
print(f"{item['key']} - {item['fsize']} bytes")
return items
else:
print(f"列表失败: {info}")
return []
# 使用示例
if __name__ == "__main__":
# 配置你的七牛云信息
ACCESS_KEY = "your_access_key"
SECRET_KEY = "your_secret_key"
BUCKET_NAME = "your_bucket_name"
DOMAIN = "https://your.domain.com"
uploader = QiniuUploader(ACCESS_KEY, SECRET_KEY, BUCKET_NAME, DOMAIN)
# 上传单个文件
url = uploader.upload_file("test.jpg")
# 上传目录
# urls = uploader.upload_directory("images", prefix="2024")
# 列出文件
# uploader.list_files(prefix="2024")
这个脚本主要特点:
- 封装成类,用起来方便
- 自动识别文件MIME类型
- 支持单个文件和整个目录上传
- 加了进度显示和错误处理
- 可以列出已上传的文件
用之前记得装qiniu包:pip install qiniu。把你的AK、SK、桶名和域名填进去就能用了。
建议:根据实际需求调整前缀策略和文件过滤逻辑。
有开源项目,当然是先赞扬楼主的开源精神了


