Security, Tech & Programming
Python Flask CheatSheet

Python Flask CheatSheet

Flask is a python framework used to run webserver.

Flask HelloWorld

Note, the capital F in flask after import keyword and also in app =.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello World!"

app.run()

Flask live reload on code changes

To reload the flask server whenever there are changes to the files, use debug=True in app.run(), like this:

app.run(debug=True)

Flask Render Template

We can separate the output of the route return statement in a template file and use render_template function to show it, like this:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    # file home.html path is /templates/home.html
    return render_template("home.html")

Flask get vs post data variables

You can use post and get variables sent via input fields of an html form in flask by using: (don’t forget to import request from flask)

# for url / get variables
request.args.get("input_name")
# for post variables sent via form "post" method
request.form.get("input_name")

Flask Layout Hello World

The structure will be:

  • server.py
  • templates/
    • layout.html
    • home.html
  • static/
    • style.css
from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/')
def home():
    return render_template("home.html")

app.run()
<!DOCTYPE html>
<html lang="en">
<head>
    <title>this is layout.html</title>
    <link rel="stylesheet" href='{{ url_for("static", filename="style.css") }}'>
</head>
<body>
    <h1>Coming from layout.html</h1>
    {% block content %}{% endblock %}
</body>
</html>
{% extends "layout.html" %}

{% block content %}
this is block from home
{% endblock %}
h1 {
    color: red;
}

If Else condition in Jinja2 with python flask

You can add conditions in your templates using jinja2 like this:

{% if some_var %}
    the var is available (add any html here)
{% else %}
    it is not available :(
{% endif %}

Flask form difference between request.form[“var”] and request.form.get(“var”)

Both return the value of the var name specified. However, the request.form["var"] will throw an error if the field was not found (or not submitted to the page), while request.form.get("var") will return None, or else you can also specify a default value like this: request.form.get("var", "Default")

Flask redirect url_for

You can redirect to any page by passing in this as return for the route function:

    return redirect(url_for('home'))
# where home is the name of the route function to which you want to redirect

Flask Dynamic Url (optional)

We can add dynamic url like this:

@user.route('/<one>')
@user.route('/<one>/<two>')
def show(one, two=None):
    # do something here

Python Flask MySQL

Example template to execute mysql query using flask. This can be helpful forexample when submitting user form data to a database table.

from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'

mysql = MySQL(app)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == "POST":
        details = request.form
        firstName = details['fname']
        lastName = details['lname']
        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO MyUsers(firstName, lastName) VALUES (%s, %s)", (firstName, lastName))
        mysql.connection.commit()
        cur.close()
        return 'success'
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire Me!