THE SYMFONY OF THE FLASK
@allucardster

Acerca de mi
- Ingeniero de Sistemas
- +6 años de experiencia
- FrontEnd, Backend
- Streamlinesocial
- Co-fundador de SUDO
Qué es Symfony?

"Es un framework para el desarrollo de aplicaciones web basado en el patrón Modelo Vista Controlador"
Acerca del Framework
- Creado por Fabien Potencier
- Fácil de instalar y configurar
- Potente Cliente de comandos
- Ampliamente documentado
- Adaptable
- Sigue las mejores practicas
de desarrollo


- PEAR
- PHP templates
- Propel - Doctrine
- Aplicaciones y Módulos
- Composer
- Twig
- Doctrine2
- Bundles (paquetes)
Comunidad















ZONA DE CONFORT

Conceptos y Componentes
- Bundles
- Anotaciones
- Configuración
- CLI/comandos
- Routing
- ORM
- Motor de plantillas
- Formularios y Validaciones

Que es Flask?
"Es un microframework para el desarrollo de aplicaciones web escrito en Python"
Acerca del framework
- Creado por Armin Ronacher
- Inspirado en Sinatra
- Fácil de instalar y configurar
- Excelente Documentación
- Open source


WERKZEUG
Jinja2
Extensiones
- Garantiza que el núcleo
sea simple - Permite agregar y reemplazar
funcionalidades completas
Que necesitamos?
- Python 2.7.9
- virtualenv
- virtualenvwrapper
Como instalar?
:~ mkvirtualenv env
(env):~ pip install FlaskHello World
# helloworld.py
# Importar Flask
from flask import Flask
# Se crea la aplicacion
app = Flask(__name__)
# Se define una ruta para la funcion "helloWorld"
@app.route("/")
def helloWorld():
return '<h1>Hello World!</h1>'
# Ejecutar la aplicacion en http://0.0.0.0:5000
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)(env):~ python helloworld.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Flask-Script
# manage.py
from flask.ext.script import Manager
from myapp import app
manager = Manager(app)
@manager.command
def hello():
print "hello"
if __name__ == "__main__":
manager.run()Configuración
# Basic Config
app = Flask(__name__)
app.config['DEBUG'] = True
# Read and write
debug = app.debug
app.debug = TrueConfiguración
class BaseConfig(object):
TESTING = False
DEBUG = False
class DevConfig(BaseConfig):
DEBUG = True
TESTING = True
class TestConfig(BaseConfig):
DEBUG = False
TESTING = True
app.config.from_object('DevConfig')
app.config.from_pyfile('path/to/app.cfg', silent=True)
# app.cfg file
DEBUG = False
SERVER_HOST='0.0.0.0'Routing
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()Flask-Sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = emailJinja2
<!-- Variables -->
{% set foo = 'bar' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
<!-- Strings -->
{{ "Hello World" }} {{ 'It\'s good' }}
<!-- Integers - Floats -->
{{ 42 }} {{ 42.5 }}
<!-- Arrays -->
["foo", "bar", 42, 42.5]
<!-- Hashes -->
{ 'foo': 'foo', 'bar': 'bar' }
<!-- Others -->
{% set foo = True %}
{% set foo = False %}<!-- If/Else -->
{% if kenny.sick %}
Kenny is sick.
{% elseif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
<!-- Loop variables -->
{% for user in users %}
{{ loop.index }} - {{ user.username }}
{% endfor %}
{# note: commented-out template because we no longer use this
{% for user in users %}
...
{% endfor %}
#}Jinja2
# layout.html
<!doctype html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Flaskr</h1>
{% block body %}{% endblock %}
</div>{% extends "layout.html" %}
{% block body %}
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
{% endblock %}Flask-WTForms
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import DataRequired, Length
class MyForm(Form):
username = StringField('Username', validators=[DataRequired(), Length(max=255)])
first_name = StringField('First name', [Length(max=255)])
last_name = StringField('Last name', [Length(max=255)])
zip_code = StringField('Zip code', [Length(max=12)])Flask-WTForms
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
<form method=post action="/register">
<dl>
{{ render_field(form.username) }}
{{ render_field(form.email) }}
{{ render_field(form.password) }}
{{ render_field(form.confirm) }}
{{ render_field(form.accept_tos) }}
</dl>
<p><input type=submit value=Register>
</form>Preguntas?

Muchas Gracias
The Symfony of the Flask
By Richard Andres Melo Carrillo
The Symfony of the Flask
Una breve introduccion a Flask desde la vision de un Symfony Developer. @calidevco, http://calidev.co
- 979