python调用seafile接口上传文件到seafile

我的 环境:seafile 8.0.3

其他版本的接口调用还是有区别的!特别是7之前的接口和新版本接口有些参数不一样了。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/10/26 17:39
# @Author : chentufeng
# @File : upload_seafile.py
# @desc : 上传文件到云盘
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# 这是python2的。python3应该也通用,可能要小改一下,但接口调用一样


import os
import json
import requests
import sys
import commands
reload(sys)
sys.setdefaultencoding('utf-8')

class UploadFile:
    def __init__(self, url, username, password, repo_id):
        self.url = url
        self.data = {'username': username, 'password': password}
        self.token_url = '%s/api2/auth-token/'%url
        self.token = self.get_token()
        self.upload_link = '%s/api2/repos/%s/upload-link/'%(url, repo_id)

    # 获取上传链接
    @staticmethod
    def _get_upload_link(url, token):
        resp = requests.get(url, headers={'Authorization': 'Token {token}'.format(token=token)})
        print(resp)
        return resp.json()

    # 获取token
    def get_token(self):
        try:
            print('>>>>>getting token...')
            response = requests.post(self.token_url, data=self.data)
            token = json.loads(response.content.decode())
            print(token)
            return token['token']
        except KeyError as e:
            print('user login failed!')
            print(e)

    # 上传文件
    def upload_file(self, filepath, relative_path):
        # parent_dir 参数默认为空,应该是 seafile 8.0.3 开始,7之前是没有relative_path 参数的。
        print('>>>>>uploading %s...' % filepath)
        self.upload_link = self._get_upload_link(self.upload_link, self.token)
        print("上传链接是: %s"%self.upload_link)
        # print(folderpath)

        response = requests.post(
            self.upload_link, data={'filename': os.path.basename(filepath),
                               'parent_dir': '', 'relative_path': relative_path, 'replace': 1},
            files={'file': open(filepath, 'rb')},
            headers={'Authorization': 'Token {token}'.format(token=self.token)}
        )
        print(str(response))
        if str(response) == '<Response [200]>':
            print('>>>>>文件[%s]上传 success!'%filepath)
        else:
            print('>>>>>文件[%s]上传 failed!'%filepath)






if __name__ == '__main__':
	upload_file_path = "/data/aa.txt" # 需要上传的文件本地路径
	relative_path = "test"  # 指定要上传到云盘哪个路径

	base_url = 'https://yunpan.com'
	repo_id = 'xxxx' # 资料库ID
	username = 'xxxx'  # 用户名
	password = 'xxxx' # 密码
	f = UploadFile(base_url, username, password, repo_id)
	f.upload_file(upload_file_path, relative_path)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值