Flask – Python
Upcoming SlideShare
Loading in...5
×
 

Flask – Python

on

  • 3,191 views

Short apresentation about Flask and Python

Short apresentation about Flask and Python

Statistics

Views

Total Views
3,191
Views on SlideShare
2,587
Embed Views
604

Actions

Likes
10
Downloads
44
Comments
0

11 Embeds 604

http://blog.maxcnunes.net 527
https://twitter.com 25
http://harajukutech.tumblr.com 19
http://localhost 11
http://angular-rails-blog.herokuapp.com 8
http://feeds.feedburner.com 4
http://harajuku-tech.org 4
https://duckduckgo.com 2
http://www.linkedin.com 2
http://translate.googleusercontent.com 1
http://webcache.googleusercontent.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Flask – Python Flask – Python Presentation Transcript

  • 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, 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
  • VIRTUALENVInstallingpip install virtualenvConfiguringcd ~/YOUR_MAIN_FOLDERmkdir virtualenvscd virtualenvsvirtualenv NAME_YOUR_ENV --no-site-packagesActivating Deactivatingsource NAME_YOUR_ENV/bin/activate deactivate
  • 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
  • 6 LINES OF CODE ANDTHIS WORKS
  • LETS GROW THIS APP
  • THE PYTHON SQL ORM
  • 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
  • FORMS
  • 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()])
  • 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 %}
  • 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)
  • 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
  • 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
  • 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
  • RUNNINGHelper to initialize the applicationbraviinitialize_app.pyfrom braviapp import braviapp as applicationapplication.run(debug=True,port=8080)Running python initialize_app.pyLETS TRY
  • DEBUGGER
  • PUBLISHING
  • 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
  • THANKS