ݺߣ

ݺߣShare 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

More Related Content

What's hot (20)

PDF
Flask Introduction - Python Meetup
Areski Belaid
PPTX
Spring Framework Petclinic sample application
Antoine Rey
PDF
Object-oriented Programming-with C#
Doncho Minkov
PDF
Rest in flask
Hamid Feizabadi
PDF
Spring Framework - Core
Dzmitry Naskou
PDF
Web Development with Python and Django
Michael Pirnat
PPTX
Spring boot
Pradeep Shanmugam
PPTX
JavaScript Promises
L&T Technology Services Limited
PPTX
Solid principles
Monica Rodrigues
PPT
Collection Framework in java
CPD INDIA
PPTX
Springboot Microservices
NexThoughts Technologies
PDF
Web develop in flask
Jim Yeh
PPTX
jQuery
Jay Poojara
KEY
Introduction to Django
James Casey
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
PDF
Collections In Java
Binoj T E
PDF
Introduction to django framework
Knoldus Inc.
PPTX
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
PPT
Asp.net architecture
Iblesoft
Flask Introduction - Python Meetup
Areski Belaid
Spring Framework Petclinic sample application
Antoine Rey
Object-oriented Programming-with C#
Doncho Minkov
Rest in flask
Hamid Feizabadi
Spring Framework - Core
Dzmitry Naskou
Web Development with Python and Django
Michael Pirnat
Solid principles
Monica Rodrigues
Collection Framework in java
CPD INDIA
Springboot Microservices
NexThoughts Technologies
Web develop in flask
Jim Yeh
Introduction to Django
James Casey
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
Collections In Java
Binoj T E
Introduction to django framework
Knoldus Inc.
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
Asp.net architecture
Iblesoft

Similar to Flask – Python (20)

PPTX
The Django Web Application Framework 2
fishwarter
PPTX
The Django Web Application Framework 2
fishwarter
PPTX
The Django Web Application Framework 2
fishwarter
PPTX
The Django Web Application Framework 2
fishwarter
PDF
Flask intro - ROSEdu web workshops
Alex Eftimie
KEY
Approaches to mobile site development
Erik Mitchell
DOCX
Akash rajguru project report sem v
Akash Rajguru
PDF
Django - basics
University of Technology
PDF
django_introduction20141030
Kevin Wu
PPTX
individuals thought of as a group because
rijeshPatel
PDF
The Django Web Application Framework
Simon Willison
KEY
Jumpstart Django
ryates
PPTX
Django course
Nagi Annapureddy
PDF
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
PPTX
Web development with Python
Raman Balyan
PPTX
Python Code Camp for Professionals 1/4
DEVCON
KEY
Web application development with Django framework
flapiello
ODP
Why Python Web Frameworks Are Changing the Web
joelburton
KEY
LvivPy - Flask in details
Max Klymyshyn
PDF
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
The Django Web Application Framework 2
fishwarter
The Django Web Application Framework 2
fishwarter
The Django Web Application Framework 2
fishwarter
The Django Web Application Framework 2
fishwarter
Flask intro - ROSEdu web workshops
Alex Eftimie
Approaches to mobile site development
Erik Mitchell
Akash rajguru project report sem v
Akash Rajguru
django_introduction20141030
Kevin Wu
individuals thought of as a group because
rijeshPatel
The Django Web Application Framework
Simon Willison
Jumpstart Django
ryates
Django course
Nagi Annapureddy
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
Web development with Python
Raman Balyan
Python Code Camp for Professionals 1/4
DEVCON
Web application development with Django framework
flapiello
Why Python Web Frameworks Are Changing the Web
joelburton
LvivPy - Flask in details
Max Klymyshyn
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
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(['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