· 6 years ago · Sep 11, 2019, 09:20 PM
1import requests
2import json
3import sys
4import argparse
5import os.path
6from collections import OrderedDict
7
8key=None
9username=None
10settings_path = "/Settings/";
11
12# Try get settings from env variables
13try:
14 username=os.environ['username']
15except:
16 print("No env for username")
17try:
18 key=os.environ['api_key']
19except:
20 print("No env for api_key")
21
22# setup static uris
23api_token=None;
24collections_uri=None;
25api="https://api.thingiverse.com/";
26
27def load_settings():
28 global username;
29 global key;
30 global api_token;
31 global collections_uri;
32
33 if(username is None or username == ""):
34 if(os.path.isfile(settings_path + "username") == False ): #throw exception
35 raise ValueError('Username file doesnt exist and neither does env variable.')
36 #Load from file if it is there
37 with open(settings_path + 'username') as f: username = f.read();
38 if(key is None or key == ""):
39 if( os.path.isfile(settings_path + "key") == False ): #throw exception
40 raise ValueError('Api Key file doesnt exist and neither does env variable.')
41 with open(settings_path + 'key') as f: key = f.read();
42 # set global var
43 api_token="?access_token=" + key.rstrip();
44 collections_uri=api + "users/" + username.rstrip().lower() + "/collections" + api_token;
45
46
47
48def call_api(url):
49 print(url);
50 s = requests.Session(); #It creates a session to speed up the downloadsraise ValueError('A very specific bad thing happened.')
51 r=s.get(url);
52 data=r.json();
53 return data;
54
55
56def check_for_items():
57 for id in set(collection_ids):
58 uri= api + "collections/" + id + "/things" + api_token;
59 collection_items=call_api(uri)
60 for item in collection_items:
61 # store id for right use
62 item_id= str(item["id"]);
63 download_uri= item["public_url"] + "/zip"
64 if(os.path.isdir("/downloaded/" + item_id) == False):
65 os.makedirs("/downloaded/" + item_id);
66 if(os.path.isfile("/downloaded/" + item_id + "/" + item_id + ".zip") == False):
67 print("Download : " + download_uri);
68
69
70
71# Setup settings via env vars or files
72load_settings();
73
74#Grab users collections
75collections=call_api(collections_uri)
76# Cast to id array
77collection_ids=[]
78for data in collections:
79 collection_ids.append(str(data["id"]));
80
81# Check for items
82check_for_items();