-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapplication.py
More file actions
executable file
·88 lines (68 loc) · 2.46 KB
/
Copy pathapplication.py
File metadata and controls
executable file
·88 lines (68 loc) · 2.46 KB
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
# Python SDK Demo App
# Copyright 2016 Optimizely. Licensed under the Apache License
# View the documentation: http://optimize.ly/py-sdk
from __future__ import print_function
import csv
import json
import os
from operator import itemgetter
from optimizely_config_manager import OptimizelyConfigManager
from optimizely_entity_conf import PROJECT_ID, EXPERIMENT_KEY, EVENT_KEY
from flask import Flask, render_template, request
application = Flask(__name__, static_folder='images')
application.secret_key = os.urandom(24)
config_manager = OptimizelyConfigManager(PROJECT_ID)
def build_items():
items = []
reader = csv.reader(open('items.csv', 'r'))
for line in reader:
items.append({'name': line[0],
'color': line[1],
'category': line[2],
'price': int(line[3][1:]),
'imageUrl': line[4]})
return items
# render homepage
@application.route('/')
def index():
items = build_items()
return render_template('index.html', data=items)
# display items
@application.route('/shop', methods=['GET', 'POST'])
def shop():
user_id = request.form['user_id']
# compute variation_key
variation_key = config_manager.get_obj().activate(EXPERIMENT_KEY, user_id)
# load items
sorted_items = build_items()
# sort by price
if variation_key == 'price':
print("In variation 1")
sorted_items = sorted(sorted_items, key=itemgetter('price'))
# sort by category
if variation_key == 'category':
print("In variation 2")
sorted_items = sorted(sorted_items, key=itemgetter('category'))
return render_template('index.html',
data=sorted_items, user_id=user_id, variation_key=variation_key)
# process a purchase event
@application.route('/buy', methods=['GET', 'POST'])
def buy():
user_id = request.form['user_id']
# track conversion event
config_manager.get_obj().track(EVENT_KEY, user_id)
return render_template('purchase.html')
# webhook logic
@application.route('/webhook', methods=['POST'])
def webhook_event():
data = request.get_json()
event_type = data['event']
# use CDN URL from webhook payload
if event_type == 'project.datafile_updated':
url = data['data']['cdn_url']
config_manager.set_obj(url)
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
return json.dumps({'success':False}), 400, {'ContentType':'application/json'}
if __name__ == '__main__':
application.debug = True
application.run(port=4001)