1+ import os , time , json
2+ import posixpath as path
3+
4+ import requests
5+
6+ from api .API_ingest import shelterluv_db
7+
8+
9+ # from config import engine
10+ # from flask import current_app
11+ # from sqlalchemy.sql import text
12+
13+ BASE_URL = 'http://shelterluv.com/api/'
14+
15+
16+ try :
17+ from secrets_dict import SHELTERLUV_SECRET_TOKEN
18+ except ImportError :
19+ # Not running locally
20+ from os import environ
21+
22+ try :
23+ SHELTERLUV_SECRET_TOKEN = environ ['SHELTERLUV_SECRET_TOKEN' ]
24+ except KeyError :
25+ # Not in environment
26+ # You're SOL for now
27+ print ("Couldn't get SHELTERLUV_SECRET_TOKEN from file or environment" )
28+
29+
30+
31+ headers = {
32+ "Accept" : "application/json" ,
33+ "X-API-Key" : SHELTERLUV_SECRET_TOKEN
34+ }
35+
36+ logger = print
37+
38+ def get_animal_count ():
39+ """Test that server is operational and get total animal count."""
40+ animals = 'v1/animals&offset=0&limit=1'
41+ URL = path .join (BASE_URL ,animals )
42+
43+ try :
44+ response = requests .request ("GET" ,URL , headers = headers )
45+ except Exception as e :
46+ logger ('get_animal_count failed with ' , e )
47+ return - 2
48+
49+ if response .status_code != 200 :
50+ logger ("get_animal_count " , response .status_code , "code" )
51+ return - 3
52+
53+ try :
54+ decoded = json .loads (response .text )
55+ except json .decoder .JSONDecodeError as e :
56+ logger ("get_animal_count JSON decode failed with" , e )
57+ return - 4
58+
59+ if decoded ['success' ]:
60+ return decoded ['total_count' ]
61+ else :
62+ return - 5 # AFAICT, this means URL was bad
63+
64+
65+ def filter_animals (raw_list ):
66+ """Given a list of animal records as returned by SL, return a list of records with only the fields we care about."""
67+
68+ good_keys = ['ID' , 'Internal-ID' , 'Name' , 'Type' , 'DOBUnixTime' , 'CoverPhoto' ,'LastUpdatedUnixTime' ]
69+
70+ filtered = []
71+
72+ for r in raw_list :
73+ f = {}
74+ for k in good_keys :
75+ f [k ] = r [k ]
76+ filtered .append (f )
77+
78+ return filtered
79+
80+
81+
82+
83+ def get_animals_bulk (total_count ):
84+ """Pull all animal records from SL """
85+
86+ MAX_COUNT = 100 # Max records the API will return for one call
87+
88+ # 'Great' API design - animal record 0 is the newest, so we need to start at the end,
89+ # back up MAX_COUNT rows, make our request, then keep backing up. We need to keep checking
90+ # the total records to ensure one wasn't added in the middle of the process.
91+ # Good news, the API is robust and won't blow up if you request past the end.
92+
93+ raw_url = path .join (BASE_URL , 'v1/animals&offset={0}&limit={1}' )
94+
95+ start_record = total_count - 1
96+ offset = (start_record - MAX_COUNT ) if (start_record - MAX_COUNT ) > - 1 else 0
97+
98+ while offset > - 1 :
99+
100+ url = raw_url .format (offset ,MAX_COUNT )
101+
102+ try :
103+ response = requests .request ("GET" ,url , headers = headers )
104+ except Exception as e :
105+ logger ('get_animals failed with ' , e )
106+ return - 2
107+
108+ if response .status_code != 200 :
109+ logger ("get_animal_count " , response .status_code , "code" )
110+ return - 3
111+
112+ try :
113+ decoded = json .loads (response .text )
114+ except json .decoder .JSONDecodeError as e :
115+ logger ("get_animal_count JSON decode failed with" , e )
116+ return - 4
117+
118+ if decoded ['success' ]:
119+ return decoded ['animals' ]
120+ else :
121+ return - 5 # AFAICT, this means URL was bad
122+
123+
124+
125+
126+ def sla_test ():
127+ total_count = get_animal_count ()
128+ print ('Total animals:' ,total_count )
129+
130+ b = get_animals_bulk (200 )
131+ print (len (b ))
132+
133+ f = filter_animals (b )
134+ print (f )
135+
136+ count = shelterluv_db .insert_animals (f )
137+ return count
138+
139+
140+ # if __name__ == '__main__' :
141+
142+ # total_count = get_animal_count()
143+ # print('Total animals:',total_count)
144+
145+ # b = get_animals_bulk(9)
146+ # print(len(b))
147+
148+ # f = filter_animals(b)
149+ # print(f)
150+
151+ # count = shelterluv_db.insert_animals(f)
0 commit comments