Flask

 

Simple and Practical

But first...

...what is a Framework?

Merriam Webster

"a basic conceptional structure (as of ideas)"

"a set of beliefs, ideas or rules that is used as the basis for making judgements, decisions, etc."

Oxford

"a particular set of rules, ideas, or beliefs which can be used in order to deal with problems or to decide what to do."

Collins

And what about a Web Framework?

It's a solution designed with a standardized approach for handling HTTP requests and responses, used for building Web Applications and REST APIs. In it's essence, that's what a Web Framework is.

Ivan Leon, Software Developer

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

The Pallets Project

 The “micro” means Flask aims to keep the core simple but extensible. Flask may be “micro”, but it’s ready for production use on a variety of needs.

Flask is a micro web framework written in Python.

Some Flask Extensions available at PyPi

  • Flask-RESTful
  • Flask-Admin
  • Flask-Login
  • Flask-Limiter
  • Flask-Mail
  • Flask-JIRA
  • Flask-lambda
  • Flask-ElasticUtils
  • Flask-SQLAlchemy
  • Flask-Session
  • Flask-graphql
  • Flask-Migrate
  • Flask-Caching
  • Flask-Analytics
  • Flask-Debug-Toolbar
  • flask2postman

A curated list of awesome Flask resources and plugins:

A Simple Application

""" Simple Flask Application """
from flask import Flask

app = Flask(__name__)

@app.route("/")
def f_index():
    """ Returns the Index resource. """
    return "Index\n"
    

if __name__ == "__main__":
    app.run(debug=True)
""" Simple Flask Application """
from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def f_index():
    """ Returns the Index resource. """
    return "Index\n"

  
@app.route("/home")
def f_home():
    """ Returns the Home resource. """
    username = request.args.get("username")
    if username == "ivanleoncz":
        return "Bem-vindo, Gaúcho!\n"
    elif username == "abraham":
        return "Bienvenido, Jarocho!\n"
    else:
        return "Welcome, whoever you are!\n"

      
if __name__ == "__main__":
    app.run(debug=True)

Templates

ivanleoncz@ilex: ~/git/Cellar/xalapacode/ex_2 $ tree
.
├── app.py
└── templates
    ├── layout.html
    └── todo.html

1 directory, 3 files

Directory Structure

""" Simple Flask Application """                                                
from flask import Flask, request, render_template                               
                                                                                
app = Flask(__name__)                                                           
                                                                                                                                                            
todo = {                                                                        
    "1":"Prepare XalapaCode Presentation",                                      
    "2":"Clean My Bedroom",                                                     
    "3":"Deliver Logiety Secret Project"                                                                
}                                                                               
                                                                                
@app.route("/")                                                                 
def f_index():                                                                  
    """ Returns the Index resource. """                                         
    return "Index\n"                                                            
                                                                                
                                                                                
@app.route("/todo")                                                             
def f_home():                                                                   
    """ Returns Todo List. """                                                  
    return render_template('todo.html', todo_list=todo)                         
                                                                                
                                                                                
if __name__ == "__main__":                                                      
    app.run(debug=True)

app.py

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
  </head>
  <body>
    <h2>This is part of my base template</h2>
    <br>
      {% block content %}{% endblock %}
    <br>
    <h2>This is part of my base template</h2>
  </body>
</html>

layout.html

{% extends "layout.html" %}
{% block content %}
  <h3> This is the start of my child template</h3>
  <p>Todo List</p>
  <ul>
    {% for key, value in todo_list.items() %}
        <li>{{key}}, {{value}}</li>
    {% endfor %}
  </ul>
  <h3> This is the end of my child template</h3>
{% endblock %}

todo.html

InteRESTing

from flask import Flask, request                                                                        
from flask_restful import Api, Resource                                         
from sqlalchemy import create_engine                                            
from sqlalchemy.orm import sessionmaker                                         
from database_setup import Base, Todo                                           
                                                                                
app = Flask(__name__)                                                           
api = Api(app)                                                                  
                                                                                
engine = create_engine('sqlite:///todo.db')                                     
                                                                                
Base.metadata.bind = engine                                                     
db_session = sessionmaker(bind=engine)                                          
session = db_session()                                                          
                                                                                
                                                                                
class TodoList(Resource):                                                       
                                                                                
    def get(self, _id):                                                         
        task = session.query(Todo).filter_by(number=_id).one                    
        return {_id: task}                                                      
                                                                                
    def put(self, _id):                                                         
        task = request.form['task']                                             
        query = session.query(Todo).filter_by(number=_id).one                   
        new_task = Todo(number=_id, task=task)                                  
        session.add(new_task)                                                   
        session.commit()                                                        
        return {_id: task}                                                      
                                                                                
    def delete(self, _id):                                                      
        session.query(Todo).filter_by(number=_id).delete()                      
        return {_id: "deleted"}                                                 
                                                                                
class TodoListAll(Resource):                                                    
                                                                                
    def get(self):                                                              
        all_tasks = {t.number:t.task for t in session.query(Todo).all()}        
        return {"tasks":all_tasks}                                              
                                                                                
api.add_resource(TodoList, '/api/v1/todo/<string:_id>')                         
api.add_resource(TodoListAll, '/api/v1/todo/')                                  
                                                                                
                                                                                
if __name__ == "__main__":                                                      
    app.run(debug=True)   
import sys                                                                                              
                                                                                
from sqlalchemy import Column, ForeignKey, Integer, String                      
from sqlalchemy.ext.declarative import declarative_base                         
from sqlalchemy.orm import relationship                                         
from sqlalchemy import create_engine                                            
                                                                                
Base = declarative_base()                                                       
                                                                                
class Todo(Base):                                                               
    __tablename__ = 'todo'                                                      
                                                                                
    id = Column(Integer, primary_key=True)                                      
    number = Column(Integer, nullable=False)                                    
    task = Column(String(250), nullable=False)                                  
                                                                                
engine = create_engine('sqlite:///todo.db')                                     
                                                                                
Base.metadata.create_all(engine)  

database_setup.py

  • Name: Ivan Leon
  • Nationality: Brazilian (Gaúcho)
  • Community Admin at XalapaCode
  • Software Engineer at Logiety
  • Contributor at StackOverflow

@ivanleoncz

Obrigado!

Flask

By Ivan Leon

Flask

Whats is Flask and how simple it is.

  • 123