Flask summary

import flask, os, sqlite3
from flask import render_template, request, redirect, url_for
from flask import send_from_directory
from werkzeug.utils import secure_filename
app = flask.Flask(__name__)
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html', id=id, items=listofItem)
else: # post
return render_template('index.html', id=id, items=listofItem)

if __name__ == '__main__':
app.run()
# GET
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
# get data pass via GET
if 'id' in request.args:
id = request.args['id']
# database access here
return render_template('edit.html', id=id, items=items)
else:
# get data pass via POST
# POST
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# get form data via POST
if 'id' in request.form: #'id' is the name of the input field
id = request.form['id']
# database access here
return render_template('edit.html', id=id, items=items)
# Database
# update statement
try:
db = sqlite3.connect('db.sqlite3')
cur = db.cursor()
cur.execute(“Update tab set name=? where id=?”, (item, id))
db.commit()
cur.close()
db.close()
return render_template(...)
except sqlite3.DatabaseError:
if db:
db.close()
msg = "Database error"
return render_template(...)
# insert statement
try:
db = sqlite3.connect('db.sqlite3')
cur = db.cursor()
cur.execute(“INSERT INTO Todo(Category, Description, Image, Status, AddOn)\
VALUES(?, ?, ?, ‘Pending’, datetime(‘now’, ‘localtime’))”, \
(categoryID, description, filename))
todoID = cur.lastrowid # get ID of the inserted record
db.commit()
curr.close()
db.close()
return render_template(...)
except sqlite3.DatabaseError:
if db:
db.close()
msg = "Database error"
return render_template(...)
# select statement
try:
db = sqlite3.connect('db.sqlite3')
db.row_factory = sqlite3.Row # enable the use of {{item.name}} in template
cur = db.cursor()
cur.execute(‘SELECT id, name FROM tab’)
all_rows = cur.fetchall()
cur.close()
db.close()
return render_template('index.html', items=all_rows)
except sqlite3.DataBaseError:
if db:
db.close()
msg = "Database error"
return render_template('error.html', errormsg=msg)

Flask:
db = sqlite3.connect('db.sqlite3')
db.row_factory = sqlite3.Row # enable the use of {{item.name}} in template
cur = db.cursor()
cur.execute(‘SELECT id, name FROM tab’)
all_rows = cur.fetchall()
cur.close()
db.close()
return render_template('index.html', items=all_rows)
Template:
{% if items|length > 0 %}
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
<td><a href="{{ url_for('edit', id=item.id) }}">Edit</a>
&nbsp;
<a href="{{ url_for('delete') }}">Delete</a>
</td>
</tr>
{% endfor %}
{%else%}
<tr>
<td colspan="2">No Items</td>
</tr>
{%endif%}
Flask:
@app.route('/index', methods=["GET", "POST"])
def index():
Template:
<form action="{{ url_for('index') }}" method="POST">

</form>
HTML generated: ⇒ “/index” link is generated from {{ url_for(‘index’) }}
<form action="/index" method="POST>

</form>

file upload

Flask:
@app.rotue('/index', methods=['GET', 'POST'])
def index():
if request.method == 'POST' and request.files and 'photo' in request.files:
# save file
photo = request.files['photo']
filename = secure_filename(photo.filename)
path = os.path.join('upload', filename)
photo.save(path)
@app.route('/photos/<filename>')
def get_file(filename):
return send_from_directory('uploads', filename)
Template:
<form action="{{ url_for('index') }}" method="POST" enctype="multipart/form-data" >
<p>Photo: <input name="photo" type="file"></p>
<p><input type="submit"></p>
</form>

flask module summary

Flask(name)creates a Flask application object
redirect(path)redirects user to given path when used as a return value from a decorated function
render_template(filename, var=value)renders Jinja2 template with the given filename using the given variable values and returns the rendered response as a str
requestaccesses current Request object
send_from_directory(folder, filename)sends file from given directory (1st argument) with given filename (2nd argument) when used as a return value from a decorated function
url_for(name, var=value)returns the path that is mapped to the given function name and given variable values

werkzeug module summary

secure_filename(filename)replaces all characters that have special meanings (e.g. path separators) in the given str with underscores

Flask class summary

route(path, methods=[“GET”])maps the given path to the decorated function but limits access to given list of HTTP methods (“GET” and “POST)
run()runs Flask application with debugged disabled
run(debug=True)runs Flask application with debugging enabled

Request class summary

argsreturns a dictionary of field names and their associated values from query portion of URL
filesreturns a dictionary of file upload names and their associated FileStorage objects
formreturns a dictionary of field names and their associated values
methodreturns either “GET” or “POST”

FileStorage class summary

filenamereturns name of the uploaded file
save(path)saves uploaded file to given path