Skip to content

Instantly share code, notes, and snippets.

@Kxrr
Last active January 18, 2022 08:40
Show Gist options
  • Save Kxrr/dcc564f9ac0904c7a26b6eb4240e11c2 to your computer and use it in GitHub Desktop.
Save Kxrr/dcc564f9ac0904c7a26b6eb4240e11c2 to your computer and use it in GitHub Desktop.
Webdev example for Jianguoyun
# -*- coding: utf-8 -*-
"""
* 关于坚果云的 Webdav 的配置可以参看: https://griddiary.uservoice.com/knowledgebase/articles/478287-%E5%9D%9A%E6%9E%9C%E4%BA%91-webdav-%E8%AE%BE%E7%BD%AE%E6%95%99%E7%A8%8B
* 使用前请先安装 `easywebdav` : ``pip install easywebdav``
坚果云 Webdav
============
假设有下面的坚果云目录结构
::
├── 我的坚果云
├── demo
└── file_on_cloud.txt
初始化
-----
初始化时传入 ``dirname='demo'`` 可以访问demo目录并设置其为起始目录
下载文件
-------
使用 ``RemoteClient('username', 'password', 'demo').download('file_on_cloud.txt')`` 可以下载 `file_on_cloud.txt` 文件到临时目录
.. note::
* 做成cli的形式
* 异常处理 例如密码错误和目录不存在
:Date: 2016-12-03 15:18
:Author: Kxrr
:Email: [email protected]
:LICENSE: MIT
"""
import sys
import tempfile
import logging
import os
from contextlib import contextmanager
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
log = logging.getLogger('webdav')
try:
import easywebdav
except ImportError:
sys.exit('Easywebdav required, try: pip install easywebdav')
def get_filename(path):
return os.path.split(path)[-1]
def get_extension(path):
filename = get_filename(path)
return filename.split('.')[-1]
class RemoteClient(object):
server = 'dav.jianguoyun.com'
_base_dir = ''
def __init__(self, username, password, dirname='demo'):
"""
:param username: 坚果云邮箱
:param password: 应用密码, 见 `第三方应用管理`_
:param dirname: 目录名
.. _`第三方应用管理`: https://www.jianguoyun.com/d/account#safe
"""
self._change_base_dir(dirname)
self._client = easywebdav.connect(self.server, username=username, password=password)
self.ping()
@classmethod
def _join(cls, *names):
return '/'.join(names)
def _fix_remote_path(self, path):
if self._base_dir not in path:
return self._join(self._base_dir, path)
return path
def _change_base_dir(self, dirname):
self._base_dir = self._join('dav', dirname)
def ping(self):
assert bool(self._client.ls(self._base_dir))
def upload(self, local):
"""
上传文件
:param local: 本地文件名
"""
assert os.path.exists(local)
filename = get_filename(local)
_remote = self._fix_remote_path(filename) # 远程文件和本地文件同名
log.info('[Upload] {0} => {1}'.format(local, _remote))
self._client.upload(local, _remote)
def download(self, remote_file, store_path=None):
"""
下载文件
:param remote_file: 远程文件名, 例如`file_on_cloud.txt`
:param store_path: 存储的文件名的绝对路径, 例如`/tmp/file_on_disk.txt`
"""
_remote_file = self._fix_remote_path(remote_file)
_store_path = store_path or tempfile.mktemp('.' + get_extension(_remote_file))
log.info('[Download] {0} => {1}'.format(_remote_file, _store_path))
self._client.download(_remote_file, _store_path)
return _store_path
def ls(self):
return self._client.ls(self._base_dir)
@contextmanager
def cd(self, dirname):
saved = self._base_dir
yield self._change_base_dir(dirname)
self._base_dir = saved
if __name__ == '__main__':
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment