-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.py
111 lines (90 loc) · 2.71 KB
/
serve.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import web
import json
import random
import hashlib
urls = (
'/', 'select',
'/(\w+)', 'get',
'/(\w+)/ratings', 'ratings',
)
app = web.application(urls, globals())
MAX_ACTIVE_JUICES = 10
active = {}
discarded = {}
class Recipe(object):
def __init__(self, id, ingredients):
self.id = id
self.ingredients = ingredients
self.ratings = {}
self.seen_by = set()
def to_dict(self):
return {
'id': self.id,
'ingredients': self.ingredients
}
class RecipeGenerator(object):
def __init__(self):
with file('ingredients.juice') as f:
self.ingredients = [x.strip() for x in f]
def generate(self):
ret = {}
for k in range(10):
fruit = random.choice(self.ingredients)
if fruit in ret:
ret[fruit] += 100
else:
ret[fruit] = 100
ingr = sorted(ret.items())
id = hashlib.md5(repr(ingr)).hexdigest()
recipe = Recipe(id, dict(ingr))
active[id] = recipe
return recipe
generate_recipe = RecipeGenerator().generate
def select_unseen_recipe(juicer):
return random.choice([x for x in active.values() if not juicer in x.seen_by])
class Base(object):
def __init__(self):
web.header('Content-type', 'application/json')
class select(Base):
def GET(self):
juicer = web.input()['juicer']
if not active:
recipe = generate_recipe()
elif all(juicer in x.seen_by for x in active.values()):
recipe = generate_recipe()
elif len(active) < MAX_ACTIVE_JUICES and random.random() < 0.5:
recipe = generate_recipe()
else:
recipe = select_unseen_recipe(juicer)
recipe.seen_by.add(juicer)
return json.dumps(recipe.to_dict(), indent=4)
class get(Base):
def GET(self, id):
try:
recipe = active[id]
return json.dumps(recipe.to_dict(), indent=4)
except KeyError:
raise web.notfound()
class ratings(Base):
def get_recipe(self, recipe_id):
try:
return active[recipe_id]
except KeyError:
raise web.notfound()
def GET(self, recipe_id):
recipe = self.get_recipe(recipe_id)
return json.dumps({
'id': recipe.id,
'ratings': recipe.ratings
})
def POST(self, recipe_id):
recipe = self.get_recipe(recipe_id)
data = json.loads(web.data())
juicer = data.get('juicer')
if not juicer:
raise web.badrequest()
rating = data['rating']
recipe.ratings[juicer] = int(rating)
return json.dumps({})
if __name__ == "__main__":
app.run()