Desarrollo de aplicaciones web con
Zope
Adrián Pérez de Castro —
[email protected]
V Jornadas GPUL sobre el Sistema Operativo Linux
Aplicaciones web con Zope
¿Qué es Zope?
Zope Básico
El primer paso: Instanciar Zope
Creación y edición de contenido
Dinamismo: ZPT, DTML, Python
Al César lo que es del César: Adquisición
El Zen de Zope
Más allá de lo predefinido: Productos
El ojo que todo lo ve: Usuarios y Roles
¿Qué es Zope?
De cómo alguien que se encuentra con una tecnología
decide mejorarla por considerarla poco útil
xxiiPrefaceOur story started when the economics of computing began marching us,one by one, into the Unix Gulag. We started passing notes to each other. Atfirst, they spoke of cultural isolation, of primitive rites and rituals that wethought belonged only to myth and fantasy, of depravation and humilia-tions. As time passed, the notes served as morale boosters, frequently usingblack humor based upon our observations. Finally, just as prisoners whoplot their escape must understand the structure of the prison better thantheir captors do, we poked and prodded into every crevice. To our horror,we discovered that our prison had no coherent design. Because it had nostrong points, no rational basis, it was invulnerable to planned attack. Ourrationality could not upset its chaos, and our messages became defeatist,documenting the chaos and lossage.This book is about people who are in abusive relationships with Unix,woven around the threads in the UNIX-HATERS mailing list. These notesare not always pretty to read. Some are inspired, some are vulgar, somedepressing. Few are hopeful. If you want the other side of the story, go reada Unix how-to book or some sales brochures. This book won’t improve your Unix skills. If you are lucky, maybe youwill just stop using Unix entirely.The UNIX-HATERS HistoryThe year was 1987, and Michael Travers, a graduate student at the MITMedia Laboratory, was taking his first steps into the future. For yearsTravers had written large and beautiful programs at the console of his Sym-¿Qué es Zope?
El nacimiento — 1
Charla sobre CGI de Jim Fulton, 1996
Antes de la charla: Jim no sabía sobre CGI
Camino de la charla: Jim leyó lo que pudo sobre CGI
Después de la charla: Jim no quería saber nada de CGI
Viaje de vuelta
Los aviones tienen mesas
En las mesas se pueden apoyar portátiles
Los portátiles sirven para programar
Programar permite hacer nuevos programas
¿Qué es Zope?
El nacimiento — 2
Jim Fulton trabajaba en Digital Creations
Prototipo implementado «on–the–fly»
Componentes «Open Source»:
Bobo (sistema de publicación)
Document Template (plantillas de texto)
BoboPOS (base de datos)
Producto comercial: Principia
Principia se hace libre: Noviembre 1998
Hadar Pedhazur convence a a Digital Creations para liberarlo
Los componentes de Principia forman la base de Zope
¿Qué es Zope?
Zope es… — 1
…un «framework»
Incluye de serie servicios que toda aplicación web necesita
El programador no necesita saber los detalles escabrosos
…orientado a objetos
Python es orientado a objetos
Todo es un objeto
…publicación de objetos
Petición = búsqueda de un objeto + invocación de método
Invocar un método típicamente devuelve HTML
¿Qué es Zope?
Zope es… — 2
…manejable a través de la web
Zope se puede administrar con (casi) cualquier navegador
Se maneja sin acceso al sistema de archivos del servidor
…capaz de delegar responsabilidades
Permite especificar políticas de seguridad complejas
Permisos según: objeto, clase del objeto, rol del usuario…
…persistente
BBDD almacena objetos de forma transparente
Cada petición es una transacción: soporte para deshacer
¿Qué es Zope?
Zope es… — 3
…extensible
A través de la web
Creando nuevas clases en Python
…«adquisitivo»
Un objeto puede «adquirir» atributos y comportamiento
Fácil especialización de partes de una aplicación web
…software libre
Esto es lo más importante, 8^)
¿Qué es Zope?
Zope NO es… — 1
…fácil de aprender y enseñar
Hay conceptos a los que cuesta habituarse
Es un sistema complejo
Poca documentación sobre ciertos aspectos
…extremadamente rápido
Pero funciona mejor que otros con recursos limitados
Python es rápido, pero podría serlo más
Más velocidad con Psyco (JIT), a costa de utilizar más RAM
…«chascarrillo» diario de la cafetería
Quizás a partir de hoy B^)
¿Qué es Zope?
Zope NO es… — 2
…la solución a todos los males
Sigue haciendo falta diseñar y programar
Puede haber gente con «Pyfobia» (nota: hay PHP y Perl)
…un servidor web al uso
Para esto ya tenemos Apache
Es mejor combinarlo con Apache: ¡más complejidad aún!
…especialmente respetuoso con «áéíóúñ»
El soporte internacional es relativamente reciente
Quedan componentes que trabajan mal con texto no–ASCII
Zope Básico
Instanciación, creación, edición, adquisición, dinamismo
xxiiPrefaceOur story started when the economics of computing began marching us,one by one, into the Unix Gulag. We started passing notes to each other. Atfirst, they spoke of cultural isolation, of primitive rites and rituals that wethought belonged only to myth and fantasy, of depravation and humilia-tions. As time passed, the notes served as morale boosters, frequently usingblack humor based upon our observations. Finally, just as prisoners whoplot their escape must understand the structure of the prison better thantheir captors do, we poked and prodded into every crevice. To our horror,we discovered that our prison had no coherent design. Because it had nostrong points, no rational basis, it was invulnerable to planned attack. Ourrationality could not upset its chaos, and our messages became defeatist,documenting the chaos and lossage.This book is about people who are in abusive relationships with Unix,woven around the threads in the UNIX-HATERS mailing list. These notesare not always pretty to read. Some are inspired, some are vulgar, somedepressing. Few are hopeful. If you want the other side of the story, go reada Unix how-to book or some sales brochures. This book won’t improve your Unix skills. If you are lucky, maybe youwill just stop using Unix entirely.The UNIX-HATERS HistoryThe year was 1987, and Michael Travers, a graduate student at the MITMedia Laboratory, was taking his first steps into the future. For yearsTravers had written large and beautiful programs at the console of his Sym-Instanciación
Zope Básico
Nuevo sitio = «Instancia» de Zope
% mkzopeinstance.py -d .
% $EDITOR etc/zope.conf
Ejecutar ZServer (método 1)
% bin/runzope
Ctrl-C
Ejecutar ZServer (método 2)
% bin/zopectl start
% bin/zopectl stop
DemoCómo acceder a Zope
Zope Básico
Vía web — Zope Management Interface
Basta con apuntar a http://localhost:8080
Con un cliente de FTP (!)
% ftp localhost 8021
Ideal para subir imágenes y archivos
Con un cliente WebDAV (!!)
% cadaver http://localhost:8080
No se obtiene el fuente: WebDAV–source en «zope.conf»
% cadaver http://localhost:9800
Especialmente cómodo 8^)
DemoCrear y editar — 1
Zope Básico
Creación
Desplegar el menú que reza «Select type to add…»
Elegir una opción
Rellenar el formulario
Edición
Navegar hasta el elemento que se desea editar
Elegir la pestaña «Edit»
Guardar los cambios
DemoCrear y editar — 2
Zope Básico
A través de FTP
ftp> mkdir fotos1
ftp> cd fotos
ftp> mput *.jpg
A través de WebDAV — cadaver
dav:/> mkdir fotos2
dav:/> cd fotos2
dav:/fotos2/> mput *.jpg
La prueba
http://localhost:8080/fotos1/lovers.jpg
DemoCrear y editar — 3
Zope Básico
Un poco de HTML
dav:/fotos2/> edit index_html
<html>
<head><title>Carátulas</title></head>
<body>
<p><img src=”xx.jpg”/></p>
<p><img src=”lovers.jpg”/></p>
<!-- ... -->
<p><img src=”wideworld.jpg”/></p>
</body>
</html>
Un poco trabajoso escribir cada nombre de archivo
Lo solucionamos luego… 8^)
DemoZope Básico
Dinamismo: ZPT — 1
ZPT = Zope Presentation Templates
Creamos «/ver_caratulas» con el siguiente código:
<html>
<head><title>Carátulas</title></head>
<body>
<p tal:repeat=”i here/objectValues”>
<span tal:replace=”i/title_or_id”>
TITULO_O_ID
</span>
<br/><img src=”URL”
tal:attributes=”src i/absolute_url”/>
</p>
</body>
</html>
DemoDinamismo: ZPT — 2
Zope Básico
Problema: se recorren todos los objetos
Seleccionar sólo las imágenes: expresión Python
<html>
<head><title>Carátulas</title></head>
<body>
<p tal:repeat=”i python:
here.objectValues(‘Image’)”>
<span tal:replace=”i/title_or_id”>
TITULO_O_ID
</span>
<br/><img src=”URL”
tal:attributes=”src i/absolute_url”/>
</p>
</body>
</html>
DemoDinamismo: DTML — 1
Zope Básico
DTML — Document Template Markup Lang.
Permite generar datos no–XML (i.e: CSS, LaTeX, Texto ASCII…)
Creamos «/caratulas.txt» con el siguiente código:
Listado de caratulas
====================
<dtml-in “here/objectValues”>
* <dtml-var sequence-item>
</dtml-in>
DemoDinamismo: DTML — 2
Zope Básico
Generar TeX con DTML
Creamos «/caratulas.tex» con el siguiente código:
\documentclass[11pt]{article}
\title{Listado de Caratulas \\
\begin{small} <dtml-var URL> \end{small}}
\author{Zope}
\begin{document} \maketitle
\begin{itemize}
<dtml-in expr="objectValues('Image')">
</dtml-in>
\end{itemize}
\end{document}
\item <dtml-var title_or_id>
DemoZPT vs. DTML
Zope Básico
Mejor usar ZPT, salvo cuando no aplicable
ZPTDTMLSiempre genera XML válidoGenera texto de cualquier tipoCompatible con editores visualesNecesariamente editado a manoPromueve modelo MVCMezcla lógica con presentaciónPlantillas con «slots»Plantillas anidadas por inclusiónMás fácil de aprenderPermite enviar e–mailAdquisición — 1
Zope Básico
Adquisición: búsqueda de objetos
Cuando un objeto existe: todo funciona según lo esperado
No existe: se intenta buscar el objeto
Buscando componentes de la URL «hacia arriba»
Al encontrar un componente, buscar «hacia abajo»
La petición se procesa en el contexto de otro objeto
Permite:
Reutilizar objetos
Organizar objetos
Especializar objetos
Comentarios de: Desarrollo de aplicaciones web con Zope (0)
No hay comentarios