forked from LaunchCode-Education-Archived/hello-flask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
94 lines (71 loc) · 2.36 KB
/
main.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
from flask import Flask, request, redirect
import cgi
import os
import jinja2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route("/")
def index():
template = jinja_env.get_template('hello_form.html')
return template.render()
@app.route("/hello", methods=['POST'])
def hello():
first_name = request.form['first_name']
template = jinja_env.get_template('hello_greeting.html')
return template.render(name=first_name)
@app.route('/validate-time')
def display_time_form():
template = jinja_env.get_template('time_form.html')
return template.render()
def is_integer(num):
try:
int(num)
return True
except ValueError:
return False
@app.route('/validate-time', methods=['POST'])
def validate_time():
hours = request.form['hours']
minutes = request.form['minutes']
hours_error = ''
minutes_error = ''
if not is_integer(hours):
hours_error = 'Not a valid integer'
hours = ''
else:
hours = int(hours)
if hours > 23 or hours < 0:
hours_error = 'Hour value out of range (0-23)'
hours = ''
if not is_integer(minutes):
minutes_error = 'Not a valid integer'
minutes = ''
else:
minutes = int(minutes)
if minutes > 59 or minutes < 0:
minutes_error = 'Minutes value out of range (0-59)'
minutes = ''
if not minutes_error and not hours_error:
time = str(hours) + ':' + str(minutes)
return redirect('/valid-time?time={0}'.format(time))
else:
template = jinja_env.get_template('time_form.html')
return template.render(hours_error=hours_error,
minutes_error=minutes_error,
hours=hours,
minutes=minutes)
@app.route('/valid-time')
def valid_time():
time = request.args.get('time')
return '<h1>You submitted {0}. Thanks for submitting a valid time!</h1>'.format(time)
tasks = []
@app.route('/todos', methods=['POST', 'GET'])
def todos():
if request.method == 'POST':
task = request.form['task']
tasks.append(task)
template = jinja_env.get_template('todos.html')
return template.render(title="TODOs", tasks=tasks)
app.run()