Slides16 Flask
Slides16 Flask
Practical
System
Skills
Fall 2019 edition
Leonhard Spiegelberg
[email protected]
16.99 Recap
Last lectures: Basic + more advanced python
- Basic:
Comments, Numbers, Strings, Lists, Tuples, Dictionaries,
Variables, Functions, Lambdas, Slicing, String formatting,
Control Flow(if/for/while), builtin functions
- Advanced:
Comprehensions(list/set/dict), Decorators, Generators, Higher
order functions(map/filter), Basic I/O, Modules
2 / 35
17 Flask
CS6 Practical System Skills
Fall 2019
Leonhard Spiegelberg [email protected]
17.01 What is Flask?
⇒ lightweight python framework to
quickly build web applications
Book:
Websites:
http://flask.palletsprojects.com/en/1.1.x/
http://exploreflask.com/en/latest/
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
5 / 35
17.03 The big picture
"backend"
HTTP GET /
7 / 35
17.04 Static vs. Dynamic websites
Static Dynamic
if __name__ == '__main__':
app.run()
9 / 35
17.05 A detailed look
hw.py
if __name__ == '__main__':
add debug=True here to
app.run()
enable auto reload of code
changes while you edit files
10 / 35
17.06 Defining routes in Flask
⇒ Basic idea: Return content for a route (i.e. the path + query
segment of an URI, e.g. /blog/12/03/09 )
@app.route('/blog/<int:year>/<int:month>/<title>')
def blog(title, month, year):
return '...'
Syntax is <varname>
@app.route('/blog/<int:year>/<int:month>/<title>')
def blog(title, month, year):
return 'Blog entry from {}/{}'.format(month, year)
12 / 35
17.07 Responses and error codes
⇒ each HTTP response comes with a status code. You can explicitly
define them in your Flask application:
@app.route('/404') no content will be displayed,
def make404(): because 404 error!
return 'This page yields a 404 error', 404
⇒ for complete list of HTTP status codes and their meaning confer
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
⇒ instead of explicitly returning, you may also use Flask's builtin function
abort(code, description=) to leave a route with an error code
14 / 35
17.08 Request and Response objects
⇒ when defining a route via flask, within the function a request
object is available holding details of the HTTP request
15 / 35
17.08 Request object
from flask import request
@app.route('/get',methods=['GET'])
def get_route():
response = '<p>{} request {} issued<p><p>' \
'Headers<br>{}</p>' \
'<p>Query args:<br>{}'.format(request.method,
request.full_path,
request.headers,
request.args)
return response, 200
body = '<table>'
for k, v in request.form.items():
body = '<tr><td>{}</td><td>{}</td></tr>'.format(k, v)
body += '</table>'
response = make_response(body)
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
Example:
Return a csv file via route /csv
syntax alternative to
@app.route('/csv') make_response
def csv():
return app.response_class(response='a,b,c\n1,2,3\n4,5,6',
mimetype='text/csv')
18 / 35
Templating + static files
17.10 Templates
⇒ so far: custom written responses
{{ title }} to replace
with title variable
folder structure
with default
folders for
templates and
static content url_for function to
create url relative to
static folder
23 / 35
17.11 More on templates
⇒ Jinja2 provides many helpful mechanisms like filters, macros, …
layout.html
blog.html landing_page.html
24 / 35
17.12 Template inheritance example
layout.html
<!DOCTYPE html> child.html
<html lang="en" dir="ltr"> {% extends 'layout.html' %}
<head> {% block body %}
<meta charset="utf-8"> <h1>Child example</h1>
<title>Template inheritance Block of parent replaced
example</title> with this content here.
</head> {% endblock %}
<body>
{% block body %}
<h1>Parent</h1>
<!-- empty template !--> child.html inherits from
{% endblock %} layout.html . Jinja2 replaces the
body block of the parent with the
content of child's one.
<p>q.e.d.</p>
</body>
</html> 25 / 35
HTML forms
17.13 Making websites interactive via forms
⇒ User input can be captured using forms
—> good resource on this topic:
Jon Duckett's HTML/CSS book Chapters 7 and 14
28 / 35
17.13 forms example
<form action="/dest" method="GET">
<label for="textbox">Text Box</label><br>
<input type="text" name="textbox"><br><br>
<label for="password">Password Input</label><br>
<input type="password" name="password"><br><br>
<label for="textbox">Text Area</label><br>
<textarea name="textarea"></textarea><br><br>
<label for="dropdown">Dropdown</label><br>
<select id="dropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select><br><br>
<label for="checkbox">Checkbox</label><br>
<input type="checkbox" name="checkbox"><br><br>
<label for="radio">Radio Select</label><br>
<input type="radio" name="radio">
<input type="radio" name="radio">
<input type="radio" name="radio"><br><br>
<label for="file">File</label><br>
<input type="file" name="file"><br><br>
<input type="submit" value="Submit Button">
</form> 29 / 35
17.13 Data encoding
⇒ Depending on the method (POST or GET) specified, the data of the form is
encoded in one of the following ways:
structure module as
folder with
__init__.py file!
33 / 35
17.08 Next steps
⇒ There are many extensions available for flask, e.g.
34 / 35
End of lecture.
Next class: Thu, 4pm-5:20pm @ CIT 477