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) == '':
            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)

你可能感兴趣的:(python,开发语言,seafile)