Presentacion web2py

54
web2py por Massimo Di Pierro Traducción y adaptación: Alfonso de la Guarda Reyes

description

Presentación, traducida y adaptada de la original

Transcript of Presentacion web2py

Page 1: Presentacion web2py

web2pypor Massimo Di Pierro

Traducción y adaptación:Alfonso de la Guarda Reyes

Page 2: Presentacion web2py

Contenidos

Presentación de características

Interfaz basada en web (Admin)

Aplicaciones (App) realmente simples

Ejemplos de código

Page 3: Presentacion web2py

web2py - presentación

Page 4: Presentacion web2py

web2py (nombre)

Web - to - Python

Web2.0 in Python

... lo que prefieran

I cannot just wait while unsecure java and php applications are taking over the world wide web. we need a new super python web framework

it needs to have a model-view-controller

design but be faster and more feature-packed thAn rails...

...very user friendly, require no installation, no configuration, no

shell scripting, no dependecies,MUST do everything via a web

interface...

... talk html, xml, rss, atom, json, csv, rtf, ajax, wiki, xml-rpc, rest,

mysql, postgresql, oracle...

...log exceptions, generate tickets,

compile and package applications, provide

testing and internationalization..

...have a strong focus on security, prevent SQL

injections, xss, malicious file execution and make the web more productive and secure.

to serve and protect, free and stable

I am web2py

testing interfacetesting interface

design interface

database admin interface

web based editor

www.web2py.com

Page 5: Presentacion web2py

Metas

Hacer el desarrollo web lo más simple posible

Pequeño, rápido y sólido como una roca

Seguridad

Refuerza las buenas prácticas (MVC, postbacks, ...)

Promete y mantiene compatibilidad retro-activa

No maneja dependencias externas

Sintáxis, no palabras clave

Page 6: Presentacion web2py

COLABORADORES

Sharriff AinaPhyo Arkar LwinMateusz Banach Robin Bhattacharyya Attila CsipaDenesLTimothy Farrel Bill Ferrett Nathan FreezeFrancisco GamaMarkus GritschSterling Hankins Jose JachufYounghyun Jo

Mark LarsenCJ LazellMarcel Leuthi Limodou Mark MooreNiccolo PoloStuart RackhamKyle SmithNiall Sweeny Michael WillisFred Yanowski Yarko

... Estoy seguro de olvidar a algunos... sorry.

Alfonso de la Guarda

Page 7: Presentacion web2py

En la caja (app, exe)

python 2.5

cherrypy wsgi server

gluon (core libraries)request, response, session, cache

internationalization, routes, helpers, forms, validators, template language, database API

contribsimplejson, pyrtf, feedparser,

pyRSS2Gen, memcache, markdown

Apps

admin(appadmin)

examples(appadmin)

welcomescaffolding(appadmin)

(jquery)

... ... ... T2 ...

plugins

Page 8: Presentacion web2py

Inspirado por Django

Diseño Modelo - Vista - Controlador

Objetos request, response y session

Generación de formularios

Validadores

Maneja cargas de archivos en formularios

urls.py/routes.py

{{...}} para escapar a código en vistas

Page 9: Presentacion web2py

Diferencias (con Django)

Interfaz de admin basada en web (o shell):

diseño,depuración,evaluación,ejecución

traducción,implementación,error tickets

Todo tiene defaults (vistas, rutas, etc.)

No requiere de archivos de configuración

El código es ejecutado no importado

Full Python en {{...}}

Page 10: Presentacion web2py

Inspirado por TG/Pylons

Auto-escape en vistas salvo XML() como Kid

response.flash inspirado por TG

Sintáxis DAL inspirada por SQLObjects

DAL soporta orderby, groupby, having, limitby, join, left join, operators, selects anidadospool de conexiones de SQLAlchemy.

Page 11: Presentacion web2py

Diferencias

XML(...,sanitize=True)

incluye jQuery

DAL trabaja en SQLite, PostgreSQL, MySQL, Oracle, MSSQL, FireBase and ...

Google App Engine (*)

(*) JOIN, OR, LIKE, IN no trabaja en GAE

Page 12: Presentacion web2py

Otras características

Migraciones de Bases de Datos automáticas

Sistema de Ticketing

Sistema de ayuda jerárquico (A, DIV, IMG, ...)

Menos de 300K bytes (+ apps)

3 tipos de cache (ram,disk,memcache+combinaciones)

No requiere librerías de terceros (incluye todo)

Incluye servidor cherrypy wsgi

Trabaja con (cgi), fcgi, wsgi, mod_python

Streaming de archivos integrado

Page 13: Presentacion web2py

Seguridad

Validación de URLs

Validación de Formularios

DAL previene SQL-injections

Vistas y helpers previenen XSS

Sesiones seguras cookies + uuid

Admin solo por https o localhost

Tickets

(reduce oportunidad de cometer errores)

Page 14: Presentacion web2py

web2py - admin

Page 15: Presentacion web2py

Startup

No requiere instalación

Unzip y click en web2py.(py|app|exe)

Page 16: Presentacion web2py

SHELL

$ python.py -S myapp -M

>>> print request.applicationmyapp>>> print response.status200>>> db=SQLDB(‘sqlite://storage.db’)

Page 17: Presentacion web2py

Bienvenida

Page 18: Presentacion web2py

Admin

Page 19: Presentacion web2py

Admin - sitio

Page 20: Presentacion web2py

Admin

Page 21: Presentacion web2py

about app

Page 22: Presentacion web2py

Admin - diseño

Page 23: Presentacion web2py

Admin - diseño

Page 24: Presentacion web2py

Admin - diseño

Page 25: Presentacion web2py

Admin - diseño

Page 26: Presentacion web2py

Admin - diseño

Page 27: Presentacion web2py

Edición

Page 28: Presentacion web2py

APPADMIN (db admin)

Page 29: Presentacion web2py

db log

Page 30: Presentacion web2py

Probar app

Page 31: Presentacion web2py

Traducir app

Page 32: Presentacion web2py

Visualizar tickets

Page 33: Presentacion web2py

debug

Page 34: Presentacion web2py

Google App Engine

(bastante de) DAL corre sobre GAE

app.yaml provisto

def ruta

click para implementar

Page 35: Presentacion web2py

web2py - myapp

Page 36: Presentacion web2py

Arquitectura

def index(): return “Hello Wold”

ControllerFILE: myapp/controllers/default.py

actionrequest response

minimoapp

Page 37: Presentacion web2py

Arquitectura

db=SQLDB(‘sqlite://storage.db’)

db.define_table(‘comment’, db.Field(‘body’))

db.comment.body.requires=IS_NOT_EMPTY()

ModeloFILE: myapp/models/db.py

actionrequest dictmodels request view response

Controlador VistaFILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

Page 38: Presentacion web2py

Arquitectura

db=SQLDB(‘sqlite://storage.db’)

db.define_table(‘comment’, db.Field(‘body’))

db.comment.body.requires=IS_NOT_EMPTY()

ModelFILE: myapp/models/db.py

actionrequest dictmodels request view response

Controller VistaFILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

Page 39: Presentacion web2py

Arquitectura

def index(): f=SQLFORM(db.comment) if f.accepts(request.vars): response.flash=T(’comment posted’) c=db().select(db.comment.ALL) return dict(form=f, comments=c)

Modelo Controlador VistaFILE: myapp/models/db.py FILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

actionrequest dictmodels request view response

Page 40: Presentacion web2py

Arquitectura

{{extend ‘layout.html’}}<ul> {{for comment in comments:}} <li>{{=comment.body}}</li> {{pass}}</ul> {{=form}}

Modelo Controlador VistaFILE: myapp/models/db.py FILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

actionrequest dictmodels request view response

Page 41: Presentacion web2py

Arquitectura

db=SQLDB(‘sqlite://storage.db’)

db.define_table(‘comment’, db.Field(‘body’))

db.comment.body.requires=IS_NOT_EMPTY()

def index(): f=SQLFORM(db.comment) if f.accepts(request.vars): response.flash=T(’comment posted’) c=db().select(db.comment.ALL) return dict(form=f, comments=c)

{{extend ‘layout.html’}}<ul> {{for comment in comments:}} <li>{{=comment.body}}</li> {{pass}}</ul> {{=form}}

Modelo Controlador VistaFILE: myapp/models/db.py FILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

actionrequest dictmodels request view response

Page 42: Presentacion web2py

Arquitectura

db=SQLDB(‘sqlite://storage.db’)

db.define_table(‘comment’, db.Field(‘body’))

db.comment.body.requires=IS_NOT_EMPTY()

def index(): f=SQLFORM(db.comment) if f.accepts(request.vars): response.flash=T(’comment posted’) c=db().select(db.comment.ALL) return dict(form=f, comments=c)

{{extend ‘layout.html’}}<ul> {{for comment in comments:}} <li>{{=comment.body}}</li> {{pass}}</ul> {{=form}}

Modelo Controlador VistaFILE: myapp/models/db.py FILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

actionrequest dictmodels request view response

Page 43: Presentacion web2py

Arquitectura

db=SQLDB(‘sqlite://storage.db’)

db.define_table(‘comment’, db.Field(‘body’))

db.comment.body.requires=IS_NOT_EMPTY()

def index(): f=SQLFORM(db.comment) if f.accepts(request.vars): response.flash=T(’comment posted’) c=db().select(db.comment.ALL) return dict(form=f, comments=c)

{{extend ‘layout.html’}}<ul> {{for comment in comments:}} <li>{{=comment.body}}</li> {{pass}}</ul> {{=form}}

Modelo Controlador VistaFILE: myapp/models/db.py FILE: myapp/controllers/default.py FILE: myapp/views/default/index.py

actionrequest dictmodels request view response

Page 44: Presentacion web2py

web2py – código ejem.SQLDB, insert, count, delete, update, select

SQLFORM, helpers

Page 45: Presentacion web2py

Dal

db = SQLDB(‘postgres://user:pass@hostname/db’, pools=10)

db.define_table(‘person’,db.Field(’name’,’string’))

id= db.person.insert(name=’Max’) ### SQL INSERT

query=(db.person.id==id)

db(query).count() ### SQL COUNT

db(query).delete() ### SQL DELETE

db(query).update(name=’Massimo’) ### SQL UPDATE

rows = db(query).select(orderby=db.person.name) ### SQL SELECT

print rows[0].name

Page 46: Presentacion web2py

DAL- INNER JOIN

db.define_table(‘dog’,db.Field(’name’))

db.define_table(‘friendship’, db.Field(’person’,db.person), db.Field(‘dog’,db.dog))

db.friendship.insert(person=id, dog=db.dog.insert(name=’Snoopy’))

friends=(db.person.id==db.friendship.person)&(db.dog.id==db.friendship.dog)

rows = db(friends).select(db.person.name, db.dog.name)

for row in rows: print row.person.name, ’is friend of’, row.dog.name

Page 47: Presentacion web2py

DAL - LEFT JOIN

query=(db.person.id>0)

friends=(db.person.id==db.friendship.person)&(db.dog.id==db.friendship.dog)

rows = db(query).select(db.person.name, db.dog.name, left=db.dog.on(friends))

for row in rows: print row.person.name, ’is friend of’, row.dog.name or ‘nobody’

Page 48: Presentacion web2py

Queries complejos

query = (db.person.id==1)|((db.person.id==2)&(db.person.name==’Max’))

query = (db.person.id==db.friendship.person)&(db.dog.id==db.friendship.dog)

query = db.person.name.lower().like(‘m%’)

query = (db.person.id.belongs(db()._select(db.friendship.person))

query = (db.person.birth.year()+1==2008)

rows = db(query).select()

Page 49: Presentacion web2py

DAL - I/o

Input

db.person.import_from_csv_file(open(filename,’rb’))

Select

rows = db(...).select(...,orderby=...,groupby=...,having=...,limitby=...,cache=...)

Output in CSV

print str(rows)

Output in HTML

print rows.xml()

Page 50: Presentacion web2py

SQLFORM

db.person.name.requires=IS_NOT_IN_DB(db,db.person.name)

db.friendship.person.requires=IS_IN_DB(db,db.person.id,’%(name)s’)

form = SQLFORM(db.friendship)

if form.accepts(request.vars, session): response.flash=’record inserted’

elif form.errors: response.flash=’form errors’

{{=form}}

make dropboxes

Page 51: Presentacion web2py

HELPERs

form = FORM(TABLE(TR(TD(INPUT(_name=’n’))),TR(TD(INPUT(_type=’submit’)))))

form[0][1][0][‘_class’]=’myclass’

if form.accepts(request.vars, session): response.flash=’record inserted’

elif form.errors: response.flash=’form errors’

{{=form}}

FORM

TABLE

TR TR

TD TD

INPUT INPUT

Page 52: Presentacion web2py

T2

Extended CRUD: t2.create, t2.display, t2.update, t2.delete, t2.itemize, t2.search

def create_person(): return dict(form=t2.create(db.person))

Authentication, Authorization, and Group Based Access Control

def login(): return dict(form=t2.login())

@t2.requires_login() # decorator

Attachments, Comments, and Reviews

def view_person(): return dict(p=t2.display(db.person),c=t2.comments(db.person))

Page 53: Presentacion web2py

Conclusiones

web2py está aquí

web2py es estable desde Oct 2007

web2py cada día tiene nuevas característ.

web2py se mueve al siguiente nivel(T2.T3.)

Al usarlo, te divertirás de verdad!!!

Page 54: Presentacion web2py

Hay miles deUsuarios web2py

Unete al Google group!