This repository has been archived by the owner on Feb 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dochub_api.py
68 lines (55 loc) · 2.28 KB
/
dochub_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import logging
import platform
import functools
import requests
from version import VERSION
logger = logging.getLogger("dochub_api")
class DochubAPI(requests.Session):
def __init__(self, token, base_url, *args, **kwargs):
self.base_url = base_url
super(DochubAPI, self).__init__(*args, **kwargs)
self.headers['Authorization'] = 'Token ' + token
self.headers['User-Agent'] = 'docfub {version} {os} {arch}'.format(
version=VERSION,
os=platform.system(),
arch=platform.machine(),
)
def post(self, path, *args, **kwargs):
full_url = self.base_url + path
r = super(DochubAPI, self).post(full_url, *args, **kwargs)
r.raise_for_status()
return r
def get(self, path, *args, **kwargs):
full_url = self.base_url + path
r = super(DochubAPI, self).get(full_url, *args, **kwargs)
r.raise_for_status()
return r
def get_tree(self):
logger.info("Download site tree")
return self.get("/api/tree/").json()
@functools.lru_cache(maxsize=256)
def get_course(self, slug):
logger.info("Download course page %s", slug)
api_path = "/api/courses/{slug}/".format(slug=slug)
return self.get(api_path).json()
@functools.lru_cache(maxsize=64)
def get_document(self, doc_id):
logger.info("Download document %d", doc_id)
api_path = "/api/documents/{doc_id}/original/".format(doc_id=doc_id)
return self.get(api_path).content
def add_document(self, course_slug, name, filename, file):
logger.info("Upload document %s in %s", name, course_slug)
api_path = "/api/documents/"
try:
res = self.post(api_path,
data={'name': name, 'course': course_slug,
'description': '_Uploadé avec docfub_'},
files={'file': (filename, file)})
except:
logger.exception("Upload document %s in %s", name, course_slug)
raise
# We modified the course, so we need to evict its cache.
# functools.clear_cache currently does not allow to evict a single
# entry, therefore we have to clear everything
self.get_course.cache_clear()
return res