系统集成实战:seafile

发布时间:2024年01月22日

前言

????????Seafile是一款强大优秀的云同步软件,拥有跨平台文件同步、移动端文件访问、挂载盘、文件共享和权限控制、文件锁定、文件版本管理和资料库镜像、在线编辑和协同编辑、审计日志等功能。

? ? ? ? 为了进一步扩展它的可用业务,并将其集成到其他业务系统中。本文将给出一个python demo,其目的在于使用本地部署的seafile系统接口,将seafile功能通过api调用的形式拉出来单独进行操作。

demo

? ? ? ? 这里集成了seafile api2及api/v2.1两款系统接口,为第三方系统+seafile的融合开发提供帮助。

? ? ? ? 该代码仅用于学习分享目的,请勿滥用!

import os
import requests

# 你的seafile信息
# 用户名、密码、项目地址根目录
username = 'xxx@qq.com'
password = 'xxxxxxx'
begin_url = 'http://127.0.0.1:1111/'


class SeafileControl:
    def __init__(self):
        self.token = self.get_token()
        # 设置请求requests session保持对象
        self.session = requests.session()

    # token获取
    def get_token(self):
        headers = {'Content-Type': 'application/json'}
        datas = {'username': username, 'password': password}
        token = ''
        try:
            r = self.session.post(begin_url + 'api2/auth-token/', json=datas, headers=headers)
            print(r.json())
            token = r.json()['token']
        except Exception as e:
            print(e)
        finally:
            return token

    # 列出所有帐户
    def account_all(self):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        r = self.session.get(begin_url + 'api2/accounts/', headers=headers)
        return r.json()

    # 获得账户信息
    def account_msg(self, account):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json',
                   'Authorization': a}  
        r = self.session.get(begin_url + 'api2/accounts/' + account, headers=headers)
        return r.json()

    # 创建用户
    def accout_create(self, AccountName):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}
        # 给予默认密码xxxx
        datas = {'password': 'xxxx'}
        response = self.session.put(begin_url + 'api2/accounts/' + AccountName + '/', json=datas, headers=headers)
        return response.text

    # 更新账户
    def account_update(self, AccountName):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        datas = {'password': '5999996', 'is_staff': 'true', 'storage': '1073741824'}
        response = self.session.put(begin_url + 'api2/accounts/' + AccountName + '/', json=datas, headers=headers)
        return response.text

    # 删除账户
    def account_delete(self, AccountName):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        response = self.session.delete(begin_url + 'api2/accounts/' + AccountName + '/', headers=headers)
        return response.text

    def link_get(self):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        response = self.session.get(begin_url + 'api2/shared-links', headers=headers)
        return response.text

    # 查询所有库
    def repos_all(self):
        a = 'Token ' + self.token
        headers = {'Authorization': a}  
        response = self.session.get(begin_url + 'api/v2.1/repos/', headers=headers)
        repos = {}
        for r in response.json()['repos']:
            repos.update({r['repo_name']: r['repo_id']})
        return repos

    # 增加库
    def repos_Insert(self, repos_name):
        a = 'Token ' + self.token
        headers = {"Authorization": a, "Accept": "application/json; indent=4",
                   "content-type": "application/x-www-form-urlencoded"}  
        datas = {'name': repos_name, 'desc': 'new library'}
        response = self.session.post(begin_url + 'api2/repos/', headers=headers, data=datas)
        key = response.text
        return key.replace('"', '')

    # 删除库
    def repos_Delete(self, repos_id):
        a = 'Token ' + self.token
        headers = {"Authorization": a, "Accept": "application/json; indent=4",
                   "content-type": "application/x-www-form-urlencoded"}  
        response = self.session.delete(begin_url + 'api2/repos/' + repos_id + '/', headers=headers)
        return response.text

    # 查询库/目录下的文件
    def file_all(self, repos_id, root_url):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        response = self.session.get(begin_url + 'api/v2.1/repos/' + repos_id + '/dir/?p=/{}&with_thumbnail=true'.format(root_url),
                         headers=headers)
        repos = {}
        for r in response.json()['dirent_list']:
            repos_type = r['type']
            if repos_type not in repos:
                repos.update({repos_type: []})
            repos[repos_type].append(r['name'])
        return repos

    # 上传文件
    def file_Insert(self, repos_id, file_name, loca_file_url):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        r = self.session.get(begin_url + 'api2/repos/' + repos_id + '/upload-link/', headers=headers)
        key = r.text.replace('"', '')
        headers = {"Authorization": a}  
        file = {'file': (file_name, open(loca_file_url, 'rb')), 'parent_dir': '/'}
        response = self.session.post(key, files=file, headers=headers)
        return response.text

    # 上传目录
    def root_Insert(self, repos_id, root_name):
        a = 'Token ' + self.token
        headers = {'Authorization': a}  
        data = {'operation': 'mkdir'}
        r = self.session.post(begin_url + 'api2/repos/' + repos_id + '/dir/?p=/{}'.format(root_name), data=data, headers=headers)
        return r.text

    # 文件更新
    def file_Update(self, repos_id, file_name, loca_file_url):
        a = 'Token ' + self.token
        headers = {'Content-Type': 'application/json', 'Authorization': a}  
        r = self.session.get(begin_url + 'api2/repos/' + repos_id + '/update-link/?p=' + '/', headers=headers)
        key = r.text.replace('"', '')
        headers = {"Authorization": a}  
        file = {'file': (file_name, open(loca_file_url, 'rb')), 'parent_dir': '/', 'replace': 1,
                'target_file': '/' + file_name}
        response = self.session.post(key + '?ret-json=1', files=file, headers=headers)
        return response.text

    # 文件下载
    def file_DownLoad(self, repos_id, file_name):
        a = 'Token ' + self.token
        headers = {"Authorization": a}  
        r = self.session.get(begin_url + 'api2/repos/' + repos_id + '/file/?p=/' + file_name, headers=headers)
        ret = False
        try:
            # 分解目录路径和文件名
            dir_path = os.path.dirname(file_name)

            if not os.path.exists(dir_path):
                os.mkdir(dir_path)

            url = r.text.replace('"', '')
            target = self.session.get(url)
            f = open('DownLoad\\' + file_name, 'wb')
            # 将下载到的图片数据写入文件
            f.write(target.content)
            f.close()
            ret = True
        except Exception as e:
            print(e)
        finally:
            return ret, r.text

    # 文件重命名
    def root_Rename(self, repos_id, old_name, new_name):
        a = 'Token ' + self.token
        headers = {"Authorization": a}  
        datas = {'operation': 'rename', 'newname': new_name}
        r = self.session.post(begin_url + 'api/v2.1/repos/' + repos_id + '/dir/?p=/' + old_name, headers=headers, data=datas)
        return r.text

    # 文件重命名
    def file_Rename(self, repos_id, old_name, new_name):
        a = 'Token ' + self.token
        headers = {"Authorization": a}  
        datas = {'operation': 'rename', 'newname': new_name}
        r = self.session.post(begin_url + 'api/v2.1/repos/' + repos_id + '/file/?p=/' + old_name, headers=headers, data=datas)
        return r.text

    # 文件移动
    def file_Move(self, repos_id, file_url, file_name, target_repos_id, target_url):
        a = 'Token ' + self.token
        headers = {"Authorization": a}  
        data = {"src_repo_id": repos_id, "src_parent_dir": file_url, "src_dirents": file_name,
                "dst_repo_id": target_repos_id,
                "dst_parent_dir": target_url}
        r = self.session.post(begin_url + 'api/v2.1/repos/sync-batch-move-item/', headers=headers, data=data)
        return r.text

    # 文件复制
    def file_Copy(self, repos_id, file_url, file_name, target_repos_id, target_url):
        a = 'Token ' + self.token
        headers = {"Authorization": a}  
        data = {"src_repo_id": repos_id, "src_parent_dir": file_url, "src_dirents": file_name,
                "dst_repo_id": target_repos_id,
                "dst_parent_dir": target_url}
        r = self.session.post(begin_url + 'api/v2.1/repos/sync-batch-copy-item/', headers=headers, data=data)
        return r.json()

    # 文件删除
    def file_Delete(self, repos_id, file_url):
        a = 'Token ' + self.token
        headers = {"Authorization": a, "Accept": "application/json; indent=4",
                   "content-type": "application/x-www-form-urlencoded"}  
        r = self.session.delete(begin_url + 'api2/repos/' + repos_id + '/file/?p=' + file_url, headers=headers)
        return r.text

    # 文件创建
    def file_Create(self, repos_id, file_url):
        a = 'Token ' + self.token
        headers = {"Authorization": a, "Accept": "application/json; indent=4",
                   "content-type": "application/x-www-form-urlencoded"}  
        datas = {'operation': 'create'}
        r = self.session.post(begin_url + 'api2/repos/' + repos_id + '/file/?p=' + file_url, headers=headers, data=datas)
        return r.text

    # 文件历史查询
    def file_History(self, repos_id, file_url):
        a = 'Token ' + self.token
        headers = {"Authorization": a, "Accept": "application/json; indent=4",
                   "content-type": "application/x-www-form-urlencoded"}  
        r = self.session.get(begin_url + 'api2/repos/' + repos_id + '/file/history/?p=' + file_url, headers=headers)
        return r.text


if __name__ == '__main__':
    # token获得
    seafile = SeafileControl()
    print('token持续时长24小时,当前值为:', seafile.token)

    # 账户操作
    # accounts = seafile.account_all()
    # print(accounts)
    #
    # for account in accounts:
    #     AccountMsg = seafile.account_msg(account['email'])
    #     print(AccountMsg)

    # links = seafile.link_get()
    # print(links)

    while True:
        repos_list = seafile.repos_all()
        print(repos_list)
        print('请选择您操作的方向:1为库操作,2为文件操作')
        menue = input()
        if menue == '1':
            print('请选择您要进行的操作:1为创建库、2为删除库')
            ch = input()
            if ch == '1':
                repos_name = input('新库名称:')
                back = seafile.repos_Insert(repos_name)
                print(back)
            elif ch == '2':
                repos_name = input('要删除的库名称:')
                repos_id = repos_list[repos_name]
                back = seafile.repos_Delete(repos_id)
                print(back)
        if menue == '2':
            print('需要对哪个库进行操作?')
            repos_name = input()
            repos_id = repos_list[repos_name]
            file_list = seafile.file_all(repos_id, '')
            print(file_list)
            while True:
                print(
                    '请选择您要进行的操作:0为创建空目录、1为上传文件、2为更新文件、3为下载文件、4为重命名文件、5为移动文件、6为拷贝文件、7为删除文件、8为创建文件(为空)、9为获取文件历史、10为查找目录文件、11为重命名目录')

                check = input()
                if check == '0':
                    root_name = input('文件夹名:')
                    back = seafile.root_Insert(repos_id, root_name)
                    print(back)
                elif check == '1':
                    file_name = input('文件名:')
                    loca_file_url = input('文件地址:')
                    back = seafile.file_Insert(repos_id, file_name, loca_file_url)
                    print(back)
                elif check == '2':
                    file_name = input('文件名:')
                    loca_file_url = input('文件地址:')
                    back = seafile.file_Update(repos_id, file_name, loca_file_url)
                    print(back)
                elif check == '3':
                    file_url = input('需要下载的文件名:')
                    ret, back = seafile.file_DownLoad(repos_id, file_url)
                    print(back)
                elif check == '4':
                    old_name = input('旧文件名:')
                    new_name = input('新文件名:')
                    back = seafile.file_Rename(repos_id, old_name, new_name)
                    print(back)
                elif check == '5':
                    target_repos = input('目标库:')
                    file_url = input('目标文件所在地址')
                    file_name = input('目标文件').split('|')
                    target_repos_id = repos_list[target_repos]
                    target_url = input('目标目录:')
                    back = seafile.file_Move(repos_id, file_url, file_name, target_repos_id, target_url)
                    print(back)
                elif check == '6':
                    target_repos = input('目标库:')
                    file_url = input('目标文件所在地址')
                    file_name = input('目标文件').split('|')
                    target_repos_id = repos_list[target_repos]
                    target_url = input('目标目录:')
                    back = seafile.file_Copy(repos_id, file_url, file_name, target_repos_id, target_url)
                    print(back)
                elif check == '7':
                    file_url = input('需要删除的文件名:')
                    back = seafile.file_Delete(repos_id, file_url)
                    print(back)
                elif check == '8':
                    file_url = input('需要创建的文件名(注意文件内容将为空):')
                    back = seafile.file_Create(repos_id, file_url)
                    print(back)
                elif check == '9':
                    file_url = input('需要查看的文件名:')
                    back = seafile.file_History(repos_id, file_url)
                    print(back)
                elif check == '10':
                    root_url = input('查看目录:')
                    back = seafile.file_all(repos_id, root_url)
                    print(back)
                elif check == '11':
                    old_name = input('旧目录名:')
                    new_name = input('新目录名:')
                    back = seafile.root_Rename(repos_id, old_name, new_name)
                    print(back)
                else:
                    break
                print('----------------- 操作分割线 -----------------')

文章来源:https://blog.csdn.net/G541788_/article/details/135759003
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。