-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapp.py
75 lines (68 loc) · 2.03 KB
/
app.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
# import modules
import os
import web
import json
import random
# Set urls
urls = (
'/', 'index',
'/api', 'api',
'/api/(.*)', 'madlibCall'
)
# Set app and render
app = web.application(urls, globals())
render = web.template.render('templates/', base="layout")
# / Route
class index(object):
def GET(self):
return render.index(output = "", title = "")
def POST(self):
form = web.input()
output = ""
title = form["title"]
for i in range(0, len(form)//2):
v = "v" + str(i) if "v" + str(i) in form else ""
b = "b" + str(i)
if v in form:
output += form[v]
if b in form:
output += form[b]
return render.index(output = output, title = title)
# /api route
class api(object):
def GET(self):
return render.api()
# /api/random route
class madlibCall(object):
def GET(self, type):
# Set headers
web.header("Access-Control-Allow-Origin", "*") # Allow all access
web.header("Content-Type", "application/json") # Set content type
if (type == "random"):
# Load json data
with open('data/templates.json') as data_file:
data = json.load(data_file)
# Return the random template
i = web.input(maxlength="100", minlength="0")
maxlength = 100
minlength = 0
# Convert
if i["maxlength"].isdigit():
maxlength = int(i["maxlength"])
if i["minlength"].isdigit():
minlength = int(i["minlength"])
if maxlength < minlength: # Can't have min greater than max!
maxlength, minlength = minlength, maxlength # Swap variables
print (minlength, maxlength)
# Filter the data based on length
new_data = [elem for elem in data["templates"] if (len(elem["blanks"]) <= maxlength and len(elem["blanks"]) >= minlength)]
# Check if elements exist
if len(new_data) < 1:
return json.dumps({"error": "Invalid length range - No templates exist"})
# Get a random index for the templates
randomIndex = random.randint(0, len(new_data) - 1)
return json.dumps(new_data[randomIndex], indent=4) # Send data
else:
return json.dumps({"error": "Invalid API call"})
if __name__ == "__main__":
app.run()