-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
79 lines (61 loc) · 1.98 KB
/
db.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
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import sqlite3
import json
DB = sqlite3.connect('etsy.db')
"""initializes the dateabase if necesssary"""
DB.executescript(
"""
CREATE TABLE IF NOT EXISTS `listings` (
`listing_id` INTEGER NOT NULL,
`request_date` INTEGER NOT NULL,
`notified_date` INTEGER,
`result` TEXT,
PRIMARY KEY(`listing_id`)
);
""")
DB.commit()
def unixtime():
return int(time.time())
def placeholders(count):
return ','.join('?' * count)
def store_listing(listing):
"""Insert (or update) a listing"""
params = (listing['listing_id'], unixtime(), json.dumps(listing))
DB.execute("""
UPDATE listings
SET request_date = ?2, result = ?3
WHERE listing_id = ?1;
""", params)
DB.execute("""
INSERT INTO listings (listing_id, request_date, result)
SELECT ?1, ?2, ?3
WHERE NOT EXISTS (SELECT 1 FROM listings WHERE listing_id = ?1);
""", params)
DB.commit()
def get_diff_listings(listings):
"""remove inactive listings and return the ones that have not yet been notified"""
listings = list(listings)
listings_ids = [item['listing_id'] for item in listings]
for listing in listings:
store_listing(listing)
DB.execute(
"""
DELETE FROM listings
WHERE listing_id NOT IN (""" + placeholders(len(listings_ids)) + """)
AND notified_date IS NOT NULL;
""", listings_ids)
DB.commit()
sql = "SELECT result FROM listings WHERE notified_date IS NULL;"
return [json.loads(row[0]) for row in DB.execute(sql)]
def mark_as_notified(listings):
"""mark all given listings as 'notified' in the database"""
listings_ids = [item['listing_id'] for item in listings]
DB.executemany(
"""
UPDATE listings
SET notified_date = ?
WHERE listing_id = ? AND notified_date IS NULL;
""", [(unixtime(), id) for id in listings_ids])
DB.commit()