SlideShare a Scribd company logo
1 of 30
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

More Related Content

What's hot (20)

Express js
Express jsExpress js
Express js
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
HTML5 & CSS3
HTML5 & CSS3 HTML5 & CSS3
HTML5 & CSS3
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Javascript
JavascriptJavascript
Javascript
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 

Similar to Flask – Python

Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsAlex Eftimie
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Hugo Hamon
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkara JUG
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationMasashi Shibata
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress WebsitesKyle Cearley
 

Similar to Flask – Python (20)

Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
 
Django crush course
Django crush course Django crush course
Django crush course
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
Django quickstart
Django quickstartDjango quickstart
Django quickstart
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
 
PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 

Flask – Python

  • 3. 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
  • 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
  • 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 – 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
  • 11. 6 LINES OF CODE AND THIS WORKS
  • 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. FORMS
  • 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 – 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>
  • 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 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
  • 26. 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
  • 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