FLASK
notes here
How to create a simple flask app:
install flask
saved as application.py
export Flask_APP=application.py
from flask import Flask, render_template, request
import datetime
app = Flask(__name__)
# HELLO
@app.route(“/”) # represents what happens when default route
def index():
headline = “Hello, world!”
return render_template(“index.html”, headline=headline)
# index.html located in templates folder,
# in html: {{ headline }}
# using Jinja2 templating language
@app.route(“hi/”)
def hi(name)():
name = name.capitalized()
return f”Hello, {name}!”
# IF ELSE
@app.route(“/newyear”)
def newyear():
now = datetime.datetime.now()
new_year = now.month == 1 and now.day == 1
return render_template(“newyear.html”, newyear=new_year)
# in newyear.html
# {% if new_year %}
Yes! Happy New Year!
# {% else %}
#
No.
# {% endif %}
# LOOPS
@app.route(“/names”)
def names():
names = [“Alice”, “Bob”, “Charlie”]
return render_template(“names.html”, names=names)
# in names.html
# {% for name in names %}
- {{ name }}
# {% endfor %}
# LINKS
@app.route(“/more”)
def more():
return render_template(“/more.html”)
# in index.html
# More
# if both pages are similar, you can use template inheritance
# eg: in layout.html
#
{% block heading %}{% endblock %}
# {% block body %}
# {% endblock %}
# in index.html
# {% extends “layout.html” %}
# FORMS
# in index.html, send form to ‘hello’
#
#
# Submit
#
@app.route(“/hello”, method=[“POST”])
def hello():
name = request.form.get(“name”)
return render_template(“hello.html”, name=name)
# in hello.html, {{ name }}
# SESSION
from flask_session import Session
app = Flask(__name__)
app.config[“SESSION_PERMANENT”] = False
app.config[“SESSION_TYPE”] = “filesystem”
Session(app)
@app.route(“/”, methods=[“GET”, “POST”])
def index():
session[“notes”] = []
if request.method == “POST”
note = request.form.get(“note”)
session[“notes”].append(note)
return render_template(“index.html”, notes=session[“notes”])