forked from SI364-Winter2018/Lecture2-Example1
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathexample.py
More file actions
51 lines (43 loc) · 1.99 KB
/
example.py
File metadata and controls
51 lines (43 loc) · 1.99 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
from flask import Flask, request
app = Flask(__name__)
app.use_reloader = True
app.debug = True
@app.route('/')
def hello_world():
return 'This is the main page. <a href="http://localhost:5000/form1">Click here to see the form.</a>'
@app.route('/form1')
def form1():
return """ <form action="http://localhost:5000/result" method='GET'>
<input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
<input type="checkbox" name="vehicle3" value="Trolley"> I have a trolley
<input type="submit" value="Submit">
</form>""" # You can imagine that you could also put this HTML in a form -- there are actually Flask-y libraries that help you use forms more efficiently, but for now we want to look at the simplest possible version to understand what's going on
@app.route('/result',methods=["GET"])
def result_form1():
if request.method == "GET":
print(request.args) # Check out your Terminal window where you're running this...
result_str = ""
for k in request.args:
result_str += "{} - {}<br><br>".format(k, request.args.get(k,""))
return result_str
return "Nothing was selected this time!"
@app.route('/form2')
def form2():
return """<form action="http://localhost:5000/letter" method='GET'>
<input type="text" name="phrase"><br>
<input type="submit" value="Submit">
"""
@app.route('/letter',methods=["GET"])
def letters_result():
if request.method == "GET":
phrase = request.args.get('phrase','')
total_number = 0
for ch in phrase:
if ch == "e":
total_number += 1
return "There were {} occurrences of the letter e in the entered phrase".format(total_number)
# Challenge: how would you change this to say "occurrence" in the case there's only 1 'e'?
return "Nothing was submitted yet... <a href='http://localhost:5000/form2'>Go submit something</a>"
if __name__ == "__main__":
app.run()