A Flask How-To Guide

A Collection of How-Tos for Learning and Using Flask

Install

$ pip install flask

Hello World

from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

Render Template

from flask import render_template 

# With Values
@app.route('/values')
def with_values():
    values = {
        'id':1,
        'status':'in progress'
    }
    return render_template('values.html', values)
<tr>
    <td>{{ id }}</td>
    <td>{{ status }}</td>
</tr>

Blueprints

from flask import Blueprint
article_blueprint = Blueprint(
    'articles', 
    __name__, 
    template_folder='templates'
)

@article_blueprint.route('/')
def articles():
    return render_template('articles/article.html')
from app.article import article_blueprint

app.register_blueprint(article_blueprint)

Request Variables

@app.route('/', methods=['GET', 'POST'])
def index():
    print(request.method) # method of GET or POST
    print(request.data) # incoming data as bytes
    print(request.json) # data if JSON turned into a dict
    print(request.headers) # incoming headers
    return "Success"

Rest API Example

GET

from flask import jsonify

# Get all Items
@app.route('/item', methods=['GET'])
def get_items():
    items = model.get_all_items()
    return jsonify({'items':items})

# Get Item by ID
@app.route('/item/<item_id>', methods=['GET'])
def get_item(item_id):
    item = model.get_item(item_id)
    return jsonify({'item':item})

POST

@app.route('/item', methods=['POST'])
def create_item():
    data = request.json
    result = model.create_item(data)
    return jsonify({'result':result})

@app.route('/item/<item_id>', methods=['POST'])
def update_item(item_id):
    data = request.json
    result = model.update_item(item_id, data)
    return jsonify({'result':result})

DELETE

@app.route('/item/<item_id>', methods=['DELETE'])
def delete_item(item_id):
    result = model.delete_item(item_id)
    return jsonify({'result':result})

Typical Project Structure

| app/
|   |-- __init__.py                
|   |-- api/ (blueprint)                      
|   |   |-- __init__.py          
|   |   |-- routes.py           
|   |   |-- models.py
|   |   |-- templates/
|   |   |   |--api/             
|   |   |   |   |-- index.html
|   |   |-- static/
|   |-- routes.py
|   |-- model.py
|   |-- templates/
|   |   |-- index.html
|   |-- static/
|   |   |-- js/
|   |   |-- css/

Redirects

from flask import redirect, url_for

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

@app.route('/redirect')
def redirect_test():
    return redirect(url_for('index'))

Session

from flask import session, redirect, url_for

app.secret_key =b'klasdfiowe90wefiuo'

@app.route('/')
def session_test():
    if 'username' in session:
        return 'Your username is {}'.format(session['username'])
    return 'Not Logged In'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="post">
            <input type=text name=username/>
            <input type=submit value=Submit/>
        </form>
    '''

Create App

from flask import Flask

def create_app():
    app = Flask(__name__)
    from api import api_blueprint
    from login import login_blueprint

    app.register_blueprint(api_blueprint)
    app.register_blueprint(login_blueprint)
    return app

app = create_app()

Config

config is dictionary like and can be modified

app = Flask(__name__)
app.config['ENV'] = 'development'
app.config['SECRET_KEY'] = 'skadjf9823ewiofw'
app.config['DB_IP_ADDR'] = '192.168.1.237'

From an Object

class BaseConfig(object):
    ENV ='development',
    DEBUG = True
    SECRET_KEY = 'skadjf9823ewiofw',
    DB_IP_ADDR = '192.168.1.237'
app = Flask(__name__)
app.config.from_object('myapp.BaseConfig')