KEMBAR78
Flask – Python | PPTX
Max Claus Nunes
maxcnunes@gmail.com
http://blog.maxcnunes.com
https://github.com/maxcnunes/flask_bravi
FLASK WHAT ?!?!?
FLASK IS
• Flask is a micro-framework for Python
• Easy to code
• Easy to configure
• Flask won’t make many decisions for
  you, such as what database to use.
• Has an excellent documentation
• RESTful
• Testable
FLASK IS
    BASED ON WERKZEUG AND JINJA 2




        WSGI               Template Engine
FLASK IS
   EXTENSIBLE AND KEEPS THE CORE SIMPLE


 • Flask-Admin            • Flask-Restless
 • Flask-Cache            • Flask-
 • Flask-OpendID            SQLAlchemy
 • Flask-Mail             • Flask-Testing
 • Flask-                 • Flask-WTF
   MongoAlchemy           • Flask-Uploads
FLASK IS
  OPEN SOURCE
LETS CODE
CONFIGURING THE ENVIRONMENT
VIRTUALENV
Installing

pip install virtualenv



Configuring

cd ~/YOUR_MAIN_FOLDER
mkdir virtualenvs
cd virtualenvs
virtualenv NAME_YOUR_ENV --no-site-packages


Activating                                Deactivating

source NAME_YOUR_ENV/bin/activate         deactivate
FLASK – THE FIRST APP
Installing   pip install Flask

Coding       # Import Flask library
             from flask import Flask

             # Initialize the app from Flask
             app = Flask(__name__)




                                                        hello.py
             # Define a route to hello_world function
             @app.route('/')
             def hello_world():
                 return 'Hello World!'

             # Run the app on http://localhost:8085
             app.run(debug=True,port=8085)

Running      python hello.py
6 LINES OF CODE AND
THIS WORKS
LETS GROW THIS APP
THE PYTHON SQL ORM
SQLALCHEMY
Installing    pip install Flask-Sqlalchemy

Coding the Model
from braviapp import db




                                                             bravibraviappmodels.py
class News(db.Model):
       # Define the properties mapped to database columns
       id = db.Column(db.Integer, primary_key = True)
       title = db.Column(db.String(100), nullable = False)
       text = db.Column(db.Text, nullable = False)

             def __init__(self, title, text):
                    self.title = title
                    self.text = text

             def __repr__(self):
                    return '<News %r>' % self.title
FORMS
WTFORMS
Installing   pip install Flask-WTF

Coding the Form




                                                            bravibraviappmodels.py
# third party imports
from flask.ext.wtf import Form, TextField, TextAreaField,
Required


class NewsCreateForm(Form):
       title = TextField('Title', [Required()])
       text = TextAreaField('Text', [Required()])
JINJA 2 - TEMPLATES
TEMPLATES – BASE HTML
<!DOCTYPE html>
<html>
     <head>
           <title>{% block title %}Flask - Bravi{% endblock %}</title>
           <link rel="stylesheet" href="/static/css/main.css" />
           {% block css %}{% endblock %}
           {% block script %}{% endblock %}
     </head>
     <body>




                                                                                              bravitemplatesbase.html
           <div id="wrapper{{ wrapper_type }}">
                      <div id="header">
                      {% block header %}
                                 <h1><a id="link-title-home"
                                 href="{{ url_for('all') }}">Bravi News</a></h1>
                      {% endblock %}
                      </div>
                      <div id="messages">
                      {% for category, msg in get_flashed_messages(with_categories=true) %}
                           <p class="messages flash-{{ category }}">{{ msg }}</p>
                      {% endfor %}
                      </div>
                      <div id="content" class="shadow">
                                 {% block content %}{% endblock %}
                      </div>
                      <div id="footer">{% block footer %}{% endblock %}</div>
           </div>
     </body>
</html>
TEMPLATES – LIST
{% extends "base.html" %}

{% block content %}
       <h2>All News</h2>




                                                      bravitemplatesnews_list.html
       <ul id="profile-results">
               {% for n in news %}
                      <li>
                            <h3>{{ n.title }}</h3>
                            {{ n.text }}
                      </li>
               {% endfor %}
       </ul>
{% endblock %}

{% block footer %}
       <a class="bt-action bt-action-edit" href="{{
url_for('create') }}">
               <span>Create</span>
       </a>
{% endblock %}
TEMPLATES – CREATE
{% extends "base.html" %}

{% block content %}




                                                                bravitemplatesnews_create.html
  <h2>Create News</h2>
  {% from "macros.html" import render_field %}
  <form method="POST" action="." class="form">
    {{ form.csrf_token }}
    {{ render_field(form.title, class="input text") }}
    {{ render_field(form.text, class="input text") }}
    <input type="submit" value="Create">
  </form>
{% endblock %}


{% block footer %}
  <a class="bt-action bt-action-list" href="{{ url_for('all')
}}">
    <span>News</span>
  </a>
{% endblock %}
JINJA 2 – MACROS - DRY
{% macro render_field(field) %}
       <div class="form_field">




                                                        bravitemplatesmacros.html
       {{ field.label(class="label") }}
       {% if field.errors %}
               {% set css_class = 'has_error' +
kwargs.pop('class', '') %}
               {{ field(class=css_class, **kwargs) }}
               <ul class="errors">
                      {% for error in field.errors %}
                      <li>{{ error|e }}</li>
                      {% endfor %}
               </ul>
       {% else %}
               {{ field(**kwargs) }}
       {% endif %}
       </div>
{% endmacro %}
VIEWS
from   flask import request, flash, redirect, url_for, render_template
from   braviapp import braviapp, db
from   braviapp.forms import NewsCreateForm
from   braviapp.models import News

@braviapp.errorhandler(404)
def not_found(error):
           flash('You tried access a page that not exists')
           return redirect(url_for('all'))




                                                                         bravibraviappviews.py
@braviapp.route('/')
def all():
           #from news_model import News
           news = News.query.all()
           return render_template('news_list.html', news=news)

@braviapp.route('/create/', methods=['GET', 'POST'])
def create():
           form = NewsCreateForm(request.form)

            # make sure data are valid
            if form.validate_on_submit():

                       news = News(form.title.data, form.text.data)
                       # save on database
                       db.session.add(news)
                       db.session.commit()

                       flash('The news has been created successfully')
                       return redirect(url_for('all'))
            return render_template('news_create.html', form=form)
CORE APP




                                              bravibraviapp__init__.PY
# third party imports
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

# Initialize the app from Flask
braviapp = Flask(__name__)
braviapp.config.from_object('settings')

db = SQLAlchemy(braviapp)

# local application imports
from braviapp import views
SETTINGS FILE
import os
_basedir = os.path.abspath(os.path.dirname(__file__))

DEBUG = False




                                                        bravisettings.py
ADMINS = frozenset(['youremail@yourdomain.com'])
SECRET_KEY = 'SECRET_KEY_FOR_SESSION_SIGNING'

# Define the path of our database inside the root
application, where 'app.db' is the database's name
SQLALCHEMY_DATABASE_URI = 'sqlite:///' +
os.path.join(_basedir, 'app.db')
DATABASE_CONNECT_OPTION = {}

CSRF_ENABLED = True
CSRF_SESSION_KEY = 'SOMETHING_IMPOSSIBLE_TO_GUEES'
SQLALCHEMY

Helper to reset the database file




                                                            braviinitialize_db.py
from app import db

# Drop all tables from db file
db.drop_all()

# Create all tables on db file,
# copying the structure from the definition on the Models
db.create_all()


Running     python initialize_db.py
RUNNING
Helper to initialize the application

braviinitialize_app.py
from braviapp import braviapp as application
application.run(debug=True,port=8080)

Running     python initialize_app.py

LETS TRY
DEBUGGER
PUBLISHING
ANY
QUESTION?
Helpful links:
• http://flask.pocoo.org
• https://github.com/mitsuhi
  ko/flask
• http://werkzeug.pocoo.org
• http://jinja.pocoo.org/docs
• http://www.sqlalchemy.org
• http://blog.maxcnunes.net
• http://www.google.com
THANKS

Flask – Python

  • 1.
  • 2.
  • 3.
    FLASK IS • Flaskis a micro-framework for Python • Easy to code • Easy to configure • Flask won’t make many decisions for you, such as what database to use. • Has an excellent documentation • RESTful • Testable
  • 4.
    FLASK IS BASED ON WERKZEUG AND JINJA 2 WSGI Template Engine
  • 5.
    FLASK IS EXTENSIBLE AND KEEPS THE CORE SIMPLE • Flask-Admin • Flask-Restless • Flask-Cache • Flask- • Flask-OpendID SQLAlchemy • Flask-Mail • Flask-Testing • Flask- • Flask-WTF MongoAlchemy • Flask-Uploads
  • 6.
    FLASK IS OPEN SOURCE
  • 7.
  • 8.
  • 9.
    VIRTUALENV Installing pip install virtualenv Configuring cd~/YOUR_MAIN_FOLDER mkdir virtualenvs cd virtualenvs virtualenv NAME_YOUR_ENV --no-site-packages Activating Deactivating source NAME_YOUR_ENV/bin/activate deactivate
  • 10.
    FLASK – THEFIRST APP Installing pip install Flask Coding # Import Flask library from flask import Flask # Initialize the app from Flask app = Flask(__name__) hello.py # Define a route to hello_world function @app.route('/') def hello_world(): return 'Hello World!' # Run the app on http://localhost:8085 app.run(debug=True,port=8085) Running python hello.py
  • 11.
    6 LINES OFCODE AND THIS WORKS
  • 12.
  • 13.
  • 14.
    SQLALCHEMY Installing pip install Flask-Sqlalchemy Coding the Model from braviapp import db bravibraviappmodels.py class News(db.Model): # Define the properties mapped to database columns id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(100), nullable = False) text = db.Column(db.Text, nullable = False) def __init__(self, title, text): self.title = title self.text = text def __repr__(self): return '<News %r>' % self.title
  • 15.
  • 16.
    WTFORMS Installing pip install Flask-WTF Coding the Form bravibraviappmodels.py # third party imports from flask.ext.wtf import Form, TextField, TextAreaField, Required class NewsCreateForm(Form): title = TextField('Title', [Required()]) text = TextAreaField('Text', [Required()])
  • 17.
    JINJA 2 -TEMPLATES
  • 18.
    TEMPLATES – BASEHTML <!DOCTYPE html> <html> <head> <title>{% block title %}Flask - Bravi{% endblock %}</title> <link rel="stylesheet" href="/static/css/main.css" /> {% block css %}{% endblock %} {% block script %}{% endblock %} </head> <body> bravitemplatesbase.html <div id="wrapper{{ wrapper_type }}"> <div id="header"> {% block header %} <h1><a id="link-title-home" href="{{ url_for('all') }}">Bravi News</a></h1> {% endblock %} </div> <div id="messages"> {% for category, msg in get_flashed_messages(with_categories=true) %} <p class="messages flash-{{ category }}">{{ msg }}</p> {% endfor %} </div> <div id="content" class="shadow"> {% block content %}{% endblock %} </div> <div id="footer">{% block footer %}{% endblock %}</div> </div> </body> </html>
  • 19.
    TEMPLATES – LIST {%extends "base.html" %} {% block content %} <h2>All News</h2> bravitemplatesnews_list.html <ul id="profile-results"> {% for n in news %} <li> <h3>{{ n.title }}</h3> {{ n.text }} </li> {% endfor %} </ul> {% endblock %} {% block footer %} <a class="bt-action bt-action-edit" href="{{ url_for('create') }}"> <span>Create</span> </a> {% endblock %}
  • 20.
    TEMPLATES – CREATE {%extends "base.html" %} {% block content %} bravitemplatesnews_create.html <h2>Create News</h2> {% from "macros.html" import render_field %} <form method="POST" action="." class="form"> {{ form.csrf_token }} {{ render_field(form.title, class="input text") }} {{ render_field(form.text, class="input text") }} <input type="submit" value="Create"> </form> {% endblock %} {% block footer %} <a class="bt-action bt-action-list" href="{{ url_for('all') }}"> <span>News</span> </a> {% endblock %}
  • 21.
    JINJA 2 –MACROS - DRY {% macro render_field(field) %} <div class="form_field"> bravitemplatesmacros.html {{ field.label(class="label") }} {% if field.errors %} {% set css_class = 'has_error' + kwargs.pop('class', '') %} {{ field(class=css_class, **kwargs) }} <ul class="errors"> {% for error in field.errors %} <li>{{ error|e }}</li> {% endfor %} </ul> {% else %} {{ field(**kwargs) }} {% endif %} </div> {% endmacro %}
  • 22.
    VIEWS from flask import request, flash, redirect, url_for, render_template from braviapp import braviapp, db from braviapp.forms import NewsCreateForm from braviapp.models import News @braviapp.errorhandler(404) def not_found(error): flash('You tried access a page that not exists') return redirect(url_for('all')) bravibraviappviews.py @braviapp.route('/') def all(): #from news_model import News news = News.query.all() return render_template('news_list.html', news=news) @braviapp.route('/create/', methods=['GET', 'POST']) def create(): form = NewsCreateForm(request.form) # make sure data are valid if form.validate_on_submit(): news = News(form.title.data, form.text.data) # save on database db.session.add(news) db.session.commit() flash('The news has been created successfully') return redirect(url_for('all')) return render_template('news_create.html', form=form)
  • 23.
    CORE APP bravibraviapp__init__.PY # third party imports from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy # Initialize the app from Flask braviapp = Flask(__name__) braviapp.config.from_object('settings') db = SQLAlchemy(braviapp) # local application imports from braviapp import views
  • 24.
    SETTINGS FILE import os _basedir= os.path.abspath(os.path.dirname(__file__)) DEBUG = False bravisettings.py ADMINS = frozenset(['youremail@yourdomain.com']) SECRET_KEY = 'SECRET_KEY_FOR_SESSION_SIGNING' # Define the path of our database inside the root application, where 'app.db' is the database's name SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db') DATABASE_CONNECT_OPTION = {} CSRF_ENABLED = True CSRF_SESSION_KEY = 'SOMETHING_IMPOSSIBLE_TO_GUEES'
  • 25.
    SQLALCHEMY Helper to resetthe database file braviinitialize_db.py from app import db # Drop all tables from db file db.drop_all() # Create all tables on db file, # copying the structure from the definition on the Models db.create_all() Running python initialize_db.py
  • 26.
    RUNNING Helper to initializethe application braviinitialize_app.py from braviapp import braviapp as application application.run(debug=True,port=8080) Running python initialize_app.py LETS TRY
  • 27.
  • 28.
  • 29.
    ANY QUESTION? Helpful links: • http://flask.pocoo.org •https://github.com/mitsuhi ko/flask • http://werkzeug.pocoo.org • http://jinja.pocoo.org/docs • http://www.sqlalchemy.org • http://blog.maxcnunes.net • http://www.google.com
  • 30.