图床,通过Python调用api上传图片到Gitlab

Lan
Lan
2022-11-07 / 1 评论 / 252 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年01月14日,已超过461天没有更新,若内容或图片失效,请留言反馈。

用过一段时间的PicGo,但是感觉太重了,为了一个上传图片去装一个软件有点太麻烦。
然后目前个人感觉也就Gitlab速度还可以一点,于是昨天翻了官方文档踩了很多坑,总算搞好了。
现将关键代码放到这里。

    file_path = datetime.datetime.now().strftime('zb_users/upload/%Y/%m/')
    headers = {'PRIVATE-TOKEN': '这里放你的项目token'}
    img = file.file.read()
    ext = file.content_type.split('/')[-1]
    file_path = urllib.parse.quote(file_path + uuid.uuid4().hex + '.' + ext).replace('/', '%2f')
    url = f'https://gitlab.com/api/v4/projects/这里放你的项目ID/repository/files/{file_path}'
    response = await requests.post(url, headers=headers, json={
        'branch': 'master',
        'content': base64.b64encode(img).decode('utf-8'),
        'author_email': 'blog@lanol.cn',
        'author_name': 'Lan',
        'encoding': 'base64',
        'commit_message': 'www.lanol.cn'
    })
    res = await response.json()

然后花了点时间写了个小前端用来上传,支持选择,拖拽,粘贴文件进行上传。
www.lanol.cn

0

评论 (1)

取消
  1. 头像
    lumstu
    Windows 10 · Google Chrome

    牛逼大佬表情

    回复