SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Flask
FlaskFlask
Flask
Mamta Kumari
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
Thanh Tuong
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 

Similar to Flask – Python (20)

Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
Alex 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 Symfony2
Hugo Hamon
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
Ankara JUG
 
Django crush course
Django crush course Django crush course
Django crush course
Mohammed El Rafie Tarabay
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
Sérgio Santos
 
Django quickstart
Django quickstartDjango quickstart
Django quickstart
Marconi Moreto
 
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 Applications
Alessandro Molina
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.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/4
DEVCON
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Masashi 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
 
PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
Fabien Potencier
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
Kyle Cearley
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
rafobarrientos
 
Flask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshopsFlask intro - ROSEdu web workshops
Flask intro - ROSEdu web workshops
Alex 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 Symfony2
Hugo Hamon
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
Ankara 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 Applications
Alessandro Molina
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.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/4
DEVCON
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Masashi 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 Websites
Kyle Cearley
 
Ad

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(['[email protected]']) 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