Skip to content

Commit 35d4bd3

Browse files
committed
test endpoint and DB inserts
1 parent 63ba9d2 commit 35d4bd3

File tree

3 files changed

+210
-0
lines changed

3 files changed

+210
-0
lines changed
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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)
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from api.api import common_api
2+
from config import engine
3+
from flask import jsonify, current_app
4+
from sqlalchemy.sql import text
5+
import requests
6+
import time
7+
from datetime import datetime
8+
9+
from sqlalchemy.dialects.postgresql import insert
10+
from sqlalchemy import Table, MetaData
11+
from pipeline import flow_script
12+
from config import engine
13+
from flask import request, redirect, jsonify, current_app
14+
from api.file_uploader import validate_and_arrange_upload
15+
from sqlalchemy.orm import Session, sessionmaker
16+
17+
18+
def insert_animals(animal_list):
19+
"""Insert animal records into shelterluv_animals table and return row count. """
20+
21+
Session = sessionmaker(engine)
22+
session = Session()
23+
metadata = MetaData()
24+
sla = Table("shelterluv_animals", metadata, autoload=True, autoload_with=engine)
25+
26+
# From Shelterluv: ['ID', 'Internal-ID', 'Name', 'Type', 'DOBUnixTime', 'CoverPhoto', 'LastUpdatedUnixTime']
27+
# In db: ['local_id', 'id' (PK), 'name', 'type', 'dob', 'photo', 'updatestamp']
28+
29+
ins_list = [] # Create a list of per-row dicts
30+
for rec in animal_list:
31+
ins_list.append(
32+
{
33+
"id": rec["Internal-ID"],
34+
"local_id": rec["ID"] if rec["ID"] else 0, # Sometimes there's no local id
35+
"name": rec["Name"],
36+
"type": rec["Type"],
37+
"dob": rec["DOBUnixTime"],
38+
"updatestamp": rec["LastUpdatedUnixTime"],
39+
"photo": rec["CoverPhoto"],
40+
}
41+
)
42+
43+
ret = session.execute(sla.insert(ins_list))
44+
45+
session.commit() # Commit all inserted rows
46+
session.close()
47+
48+
return ret.rowcount

src/server/api/admin_api.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,17 @@ def hit_gdrs():
398398
return jsonify({"scores added" : num_scores})
399399

400400

401+
402+
403+
@admin_api.route("/api/admin/test_sla", methods=["GET"])
404+
def trigger_sla_pull():
405+
406+
import api.API_ingest.shelterluv_animals
407+
408+
num_rows = api.API_ingest.shelterluv_animals.sla_test()
409+
return jsonify({"rows added" : num_rows})
410+
411+
401412
# def pdfr():
402413
# dlist = pull_donations_for_rfm()
403414
# print("Returned " + str(len(dlist)) + " rows")

0 commit comments

Comments
 (0)