forked from lighthouse-web3/lighthouse-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.py
More file actions
87 lines (78 loc) · 2.89 KB
/
Copy pathupload.py
File metadata and controls
87 lines (78 loc) · 2.89 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
from io import BufferedReader
from typing import Dict, List, Tuple
from .axios import Axios
from .utils import is_dir, walk_dir_tree, extract_file_name, NamedBufferedReader
from .config import Config
from .exceptions import LighthouseUploadError
def upload(source, token: str, tag: str = ""):
"""
Deploy a file or directory to the lighthouse network
@params {source}: str, path to file or directory
@params {token}: str, lighthouse api token
"""
# create headers
headers = {
"Authorization": f"Bearer {token}",
# "Content-Type": "multipart/form-data",
"Encryption": "false",
"Mime-Type": "application/octet-stream",
}
try:
# create http object
axios = Axios(Config.lighthouse_node + "/api/v0/add")
# create list of files to upload
if (isinstance(source, str)):
file_dict = {}
# check if source is a directory
if is_dir(source):
# walk directory tree and add files to list
file_dict["files"], root = walk_dir_tree(source)
file_dict["is_dir"] = True
file_dict["path"] = root
else:
# add file to list
file_dict["files"] = [source]
file_dict["is_dir"] = False
file_dict["path"] = source
hashData = axios.post_files(file_dict, headers)
else:
hashData = axios.post_blob(source, source.name, headers)
if len(tag):
_axios = Axios(Config.lighthouse_api + "/api/user/create_tag")
data = _axios.post({
"tag": tag,
"cid": hashData.get("Hash")
}, {
"Authorization": f"Bearer {token}", })
return {"data": hashData}
except Exception as e:
raise LighthouseUploadError(str(e)) from e
def uploadBlob(source: BufferedReader, filename: str, token: str, tag: str = ""):
"""
Upload a Buffer or readable Object
@params {source}: str, path to file or directory
@params {token}: str, lighthouse api token
"""
# create headers
headers = {
"Authorization": f"Bearer {token}",
# "Content-Type": "multipart/form-data",
"Encryption": "false",
"Mime-Type": "application/octet-stream",
}
try:
# create http object
axios = Axios(Config.lighthouse_node + "/api/v0/add")
# create list of files to upload
hashData = axios.post_blob(source, filename, headers)
if len(tag):
_axios = Axios(Config.lighthouse_api + "/api/user/create_tag")
data = _axios.post({
"tag": tag,
"cid": hashData.get("Hash")
}, {
"Authorization": f"Bearer {token}", })
return {"data": hashData}
except Exception as e:
raise LighthouseUploadError(str(e)) from e