Flask Cheat Sheet

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Flask Cheat Sheet

PIP, VENV and Flask Installation and Setup


Make sure you have Python running on your machine.
Install pip https://bootstrap.pypa.io/get-pip.py
install virtualenv > pip install virtualenv
create directory and environment
> mkdir project
> cd project
> virtualenv venv
> venv\scripts\activate
> pip install flask

when finished...deactivate
> venv\scripts\deactivate

$ export FLASK_APP=hello.py
$ flask run
* Running on http://127.0.0.1:5000/

IMPORTANT: If you are on Windows you need to use set instead of export.
Alternatively you can use python -m flask :
$ export FLASK_APP=hello.py
$ python -m flask run
* Running on http://127.0.0.1:5000/

Basic app.py
from flask import Flask, render_template
from flask import make_response
from flask import redirect
app = Flask(__name__)

@app.route("/")
def index():
return '<h1>Hello World!</h1>'
@app.route('/user/<name>')
def user(name):
return '<h1> Hello %s </h1>' % name
@app.route('/cookie')
def cookie():
response = make_response ('<h1>this document carries a cookie</h1>')
response.set_cookie('answer', '42')
return response
@app.route ('/redirect')
def redirectwebsite():
return redirect('http://www.google.com')
if __name__ == '__main__':
app.run(debug=True)

Templates
jinja2
app.py
from flask import Flask
from flask import render_template
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name= name)

index.html (template)
<h1>Hello {{ name }} from Jinja2 Template!</h1>

Variables {{ varname }} {{ varname | filter }}


{{ varname | capitalize }}

control structures
{% if user %}
Hello, {{ user }}!
{% else %}
Hello, Stranger!
{% endif %}

render list of elements


<ul>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ul>

Template Include and Inheritance


Portions of template code that need to be repeated in several places can be stored in a
separate file and included from all the templates to avoid repetition:
{% include 'common.html' %}

base template (base.html)


<html>
<head>
{% block head %}
<title>{% block title %}{% endblock %} - My Application</title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>

derived template (base.html)


pip{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style>
</style>
{% endblock %}
{% block body %}
<h1>Hello, World!</h1>
{% endblock %}

Note that the new definition of the head block, which


is not empty in the base template, uses super() to retain the original contents.

You might also like