30
Max Claus Nunes [email protected] http://blog.maxcnunes.com https:// github.com/maxcnunes/flask_bravi

Flask – Python

Embed Size (px)

DESCRIPTION

Short apresentation about Flask and Python

Citation preview

Page 2: Flask – Python

FLASK WHAT ?!?!?

Page 3: Flask – Python

• 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

Page 4: Flask – Python

FLASK IS

BASED ON WERKZEUG AND JINJA 2

WSGI Template Engine

Page 5: Flask – Python

FLASK IS

• Flask-Admin

• Flask-Cache

• Flask-OpendID

• Flask-Mail

• Flask-MongoAlchemy

EXTENSIBLE AND KEEPS THE CORE SIMPLE

• Flask-Restless

• Flask-SQLAlchemy

• Flask-Testing

• Flask-WTF

• Flask-Uploads

Page 6: Flask – Python

FLASK IS

OPEN SOURCE

Page 7: Flask – Python

LETS CODE

Page 8: Flask – Python

CONFIGURING THE ENVIRONMENT

Page 9: Flask – Python

VIRTUALENVInstalling

pip install virtualenv

Configuring

cd ~/YOUR_MAIN_FOLDERmkdir virtualenvscd virtualenvsvirtualenv NAME_YOUR_ENV --no-site-packages

Activating

source NAME_YOUR_ENV/bin/activate

Deactivating

deactivate

Page 10: Flask – Python

FLASK – THE FIRST APPInstalling pip install

FlaskCoding # Import Flask library

from flask import Flask # Initialize the app from Flaskapp = Flask(__name__) # Define a route to hello_world [email protected]('/')def hello_world():    return 'Hello World!' # Run the app on http://localhost:8085app.run(debug=True,port=8085)

Running python hello.py

hello.py

Page 11: Flask – Python

6 LINES OF CODE AND THIS WORKS

Page 12: Flask – Python

LETS GROW THIS APP

Page 13: Flask – Python

THE PYTHON SQL ORM

Page 14: Flask – Python

SQLALCHEMYInstalling pip install Flask-

Sqlalchemy

Coding the Model

from braviapp import db

class News(db.Model):# Define the properties mapped to database

columnsid = 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 = titleself.text = text

def __repr__(self):return '<News %r>' % self.title

bravi\braviapp\models.py

Page 15: Flask – Python

FORMS

Page 16: Flask – Python

WTFORMSInstalling pip install Flask-WTF

Coding the Form

# third party importsfrom flask.ext.wtf import Form, TextField, TextAreaField, Required

class NewsCreateForm(Form):title = TextField('Title', [Required()])text = TextAreaField('Text', [Required()])

bravi\braviapp\models.py

Page 17: Flask – Python

JINJA 2 - TEMPLATES

Page 18: Flask – Python

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>

<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>

bravi\templates\base.html

Page 19: Flask – Python

TEMPLATES – LIST{% extends "base.html" %}

{% block content %}<h2>All News</h2><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 %}

bravi\templates\news_list.html

Page 20: Flask – Python

TEMPLATES – CREATE{% extends "base.html" %}

{% block content %} <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 %}

bravi\templates\news_create.html

Page 21: Flask – Python

JINJA 2 – MACROS - DRY

{% macro render_field(field) %}<div class="form_field">{{ 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 %}

bravi\templates\macros.html

Page 22: Flask – Python

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'))

@braviapp.route('/')def all():

#from news_model import Newsnews = 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 validif form.validate_on_submit():

news = News(form.title.data, form.text.data)# save on databasedb.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)

bravi\braviapp\views.py

Page 23: Flask – Python

CORE APP

# 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

bravi\braviapp\__init__.PY

Page 24: Flask – Python

SETTINGS FILEimport os_basedir = os.path.abspath(os.path.dirname(__file__))

DEBUG = False

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 nameSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db')DATABASE_CONNECT_OPTION = {}

CSRF_ENABLED = TrueCSRF_SESSION_KEY = 'SOMETHING_IMPOSSIBLE_TO_GUEES'

bravi\settings.py

Page 25: Flask – Python

SQLALCHEMY

Helper to reset the database file

from 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()

bravi\initialize_db.py

Running python initialize_db.py

Page 26: Flask – Python

RUNNING

from braviapp import braviapp as applicationapplication.run(debug=True,port=8080)

bravi\initialize_app.py

Running python initialize_app.py

Helper to initialize the application

Works???LETS TRY

Page 27: Flask – Python

DEBUGGER

Page 28: Flask – Python

PUBLISHING

Page 30: Flask – Python

THANKS