Last active
September 19, 2018 17:50
-
-
Save vasinkd/5f34446753d4bcb5b714da9e1ea3846d to your computer and use it in GitHub Desktop.
I used this snippet to backup some files from my server to Yandex Disk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
#!/usr/bin/env python | |
# | |
# Based on https://github.com/TyVik/YaDiskClient | |
# Author: Kirill Vasin | |
import json | |
from requests import request | |
import os | |
disk_cred = ("user", "password") | |
FAILED_FOLDER = "failed_to_save" | |
def failover_action(prepared_data, path): | |
if not os.path.exists(FAILED_FOLDER): | |
os.makedirs(FAILED_FOLDER) | |
fail_file = os.path.join(FAILED_FOLDER, os.path.basename(path)) | |
with open(fail_file, 'w') as outfile: | |
outfile.write(prepared_data) | |
class YaDiskException(Exception): | |
"""Common exception class for YaDisk. Arg 'code' have code of HTTP Error.""" | |
code = None | |
def __init__(self, code, text): | |
super(YaDiskException, self).__init__(text) | |
self.code = code | |
def __str__(self): | |
return "{code}. {message}".format(code=self.code, message=super(YaDiskException, self).__str__()) | |
def send_data(user, data, path): | |
""" | |
data should be JSON serializable | |
""" | |
prepared_data = json.dumps(data) | |
headers = {"Accept": "*/*"} | |
url = "https://webdav.yandex.ru/" + path | |
resp = request("PUT", url, headers=headers, | |
auth=disk_cred, data=prepared_data, | |
timeout=5) | |
if resp.status_code != 201: | |
failover_action(prepared_data, path) | |
raise YaDiskException(resp.status_code, resp.content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment