Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Max Claus Nunesmaxcnunes@gmail.comhttp://blog.maxcnunes.comhttps://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...
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 IS  OPEN SOURCE
LETS CODE
CONFIGURING THE ENVIRONMENT
VIRTUALENVInstallingpip install virtualenvConfiguringcd ~/YOUR_MAIN_FOLDERmkdir virtualenvscd virtualenvsvirtualenv NAME_Y...
FLASK – THE FIRST APPInstalling   pip install FlaskCoding       # Import Flask library             from flask import Flask...
6 LINES OF CODE ANDTHIS WORKS
LETS GROW THIS APP
THE PYTHON SQL ORM
SQLALCHEMYInstalling    pip install Flask-SqlalchemyCoding the Modelfrom braviapp import db                               ...
FORMS
WTFORMSInstalling   pip install Flask-WTFCoding the Form                                                            bravib...
JINJA 2 - TEMPLATES
TEMPLATES – BASE HTML<!DOCTYPE html><html>     <head>           <title>{% block title %}Flask - Bravi{% endblock %}</title...
TEMPLATES – LIST{% extends "base.html" %}{% block content %}       <h2>All News</h2>                                      ...
TEMPLATES – CREATE{% extends "base.html" %}{% block content %}                                                            ...
JINJA 2 – MACROS - DRY{% macro render_field(field) %}       <div class="form_field">                                      ...
VIEWSfrom   flask import request, flash, redirect, url_for, render_templatefrom   braviapp import braviapp, dbfrom   bravi...
CORE APP                                              bravibraviapp__init__.PY# third party importsfrom flask import Flask...
SETTINGS FILEimport os_basedir = os.path.abspath(os.path.dirname(__file__))DEBUG = False                                  ...
SQLALCHEMYHelper to reset the database file                                                            braviinitialize_db....
RUNNINGHelper to initialize the applicationbraviinitialize_app.pyfrom braviapp import braviapp as applicationapplication.r...
DEBUGGER
PUBLISHING
ANYQUESTION?Helpful links:• http://flask.pocoo.org• https://github.com/mitsuhi  ko/flask• http://werkzeug.pocoo.org• http:...
THANKS
Upcoming SlideShare
Loading in …5
×

Flask – Python

10,562 views

Published on

Short apresentation about Flask and Python

Flask – Python

  1. 1. Max Claus Nunesmaxcnunes@gmail.comhttp://blog.maxcnunes.comhttps://github.com/maxcnunes/flask_bravi
  2. 2. FLASK WHAT ?!?!?
  3. 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. 4. FLASK IS BASED ON WERKZEUG AND JINJA 2 WSGI Template Engine
  5. 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. 6. FLASK IS OPEN SOURCE
  7. 7. LETS CODE
  8. 8. CONFIGURING THE ENVIRONMENT
  9. 9. VIRTUALENVInstallingpip install virtualenvConfiguringcd ~/YOUR_MAIN_FOLDERmkdir virtualenvscd virtualenvsvirtualenv NAME_YOUR_ENV --no-site-packagesActivating Deactivatingsource NAME_YOUR_ENV/bin/activate deactivate
  10. 10. FLASK – THE FIRST APPInstalling pip install FlaskCoding # 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. 11. 6 LINES OF CODE ANDTHIS WORKS
  12. 12. LETS GROW THIS APP
  13. 13. THE PYTHON SQL ORM
  14. 14. SQLALCHEMYInstalling pip install Flask-SqlalchemyCoding the Modelfrom braviapp import db bravibraviappmodels.pyclass 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. 15. FORMS
  16. 16. WTFORMSInstalling pip install Flask-WTFCoding the Form bravibraviappmodels.py# third party importsfrom flask.ext.wtf import Form, TextField, TextAreaField,Requiredclass NewsCreateForm(Form): title = TextField(Title, [Required()]) text = TextAreaField(Text, [Required()])
  17. 17. JINJA 2 - TEMPLATES
  18. 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. 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. 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. 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. 22. VIEWSfrom flask import request, flash, redirect, url_for, render_templatefrom braviapp import braviapp, dbfrom braviapp.forms import NewsCreateFormfrom 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. 23. CORE APP bravibraviapp__init__.PY# third party importsfrom flask import Flaskfrom flask.ext.sqlalchemy import SQLAlchemy# Initialize the app from Flaskbraviapp = Flask(__name__)braviapp.config.from_object(settings)db = SQLAlchemy(braviapp)# local application importsfrom braviapp import views
  24. 24. SETTINGS FILEimport os_basedir = os.path.abspath(os.path.dirname(__file__))DEBUG = False bravisettings.pyADMINS = frozenset([youremail@yourdomain.com])SECRET_KEY = SECRET_KEY_FOR_SESSION_SIGNING# Define the path of our database inside the rootapplication, where app.db is the databases nameSQLALCHEMY_DATABASE_URI = sqlite:/// +os.path.join(_basedir, app.db)DATABASE_CONNECT_OPTION = {}CSRF_ENABLED = TrueCSRF_SESSION_KEY = SOMETHING_IMPOSSIBLE_TO_GUEES
  25. 25. SQLALCHEMYHelper to reset the database file braviinitialize_db.pyfrom app import db# Drop all tables from db filedb.drop_all()# Create all tables on db file,# copying the structure from the definition on the Modelsdb.create_all()Running python initialize_db.py
  26. 26. RUNNINGHelper to initialize the applicationbraviinitialize_app.pyfrom braviapp import braviapp as applicationapplication.run(debug=True,port=8080)Running python initialize_app.pyLETS TRY
  27. 27. DEBUGGER
  28. 28. PUBLISHING
  29. 29. ANYQUESTION?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. 30. THANKS

×