-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathactors.py
72 lines (58 loc) · 2.32 KB
/
actors.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
from flask_bootstrap import Bootstrap5
from flask import Flask, render_template, redirect, url_for
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length
from data import ACTORS
from modules import get_names, get_actor, get_id
app = Flask(__name__)
app.secret_key = 'tO$&!|0wkamvVia0?n$NqIRVWOG'
# Bootstrap-Flask requires this line
bootstrap = Bootstrap5(app)
# Flask-WTF requires this line
csrf = CSRFProtect(app)
# with Flask-WTF, each web form is represented by a class
# "NameForm" can change; "(FlaskForm)" cannot
# see the route for "/" and "index.html" to see how this is used
class NameForm(FlaskForm):
name = StringField('Which actor is your favorite? Type a complete name.', validators=[DataRequired(), Length(10, 40)])
submit = SubmitField('Submit')
# all Flask routes below
@app.route('/', methods=['GET', 'POST'])
def index():
names = get_names(ACTORS)
# you must tell the variable 'form' what you named the class, above
# 'form' is the variable name used in this template: index.html
form = NameForm()
message = ""
if form.validate_on_submit():
name = form.name.data
if name.lower() in names:
# empty the form field
form.name.data = ""
id = get_id(ACTORS, name)
# redirect the browser to another route and template
return redirect( url_for('actor', id=id) )
else:
message = "That actor is not in our database."
return render_template('index.html', names=names, form=form, message=message)
@app.route('/actor/<id>')
def actor(id):
# run function to get actor data based on the id in the path
id, name, photo = get_actor(ACTORS, id)
if name == "Unknown":
# redirect the browser to the error template
return render_template('404.html'), 404
else:
# pass all the data for the selected actor to the template
return render_template('actor.html', id=id, name=name, photo=photo)
# 2 routes to handle errors - they have templates too
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
# keep this as is
if __name__ == '__main__':
app.run(debug=True)