forked from unisport/sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
populate.py
58 lines (46 loc) · 1.22 KB
/
populate.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
# -*- coding: utf-8 -*-
import sys
import json
from models import Product
import codecs
import urllib2
import logging
def format_price(product):
"""
Turns 0,00 into a real float
"""
try:
price = product['price'].replace(',', '.')
return float(price)
except KeyError:
return float('0.00')
def kids_true(product):
"""
Turns kids == 1 into a boolean instead
"""
try:
if product['kids'] == '1':
return True
else:
return False
except KeyError:
return False
def format_id(product):
"""
Turns the product id into an integer
"""
return int(product['id'])
def format_name(product):
"""
Ran into some weird encoding problem, tried to fix it by
ensuring correct encoding. But really, ascii in a webservice?
"""
return product['name'].encode('utf-8')
try:
resp = urllib2.urlopen('http://www.unisport.dk/api/sample/')
json_data = json.loads(resp.read())
for product in json_data['products']:
Product.create(name=format_name(product), price=format_price(product),
for_kids=kids_true(product), product_id=format_id(product))
except urllib2.URLError, e:
logging.warn(e)