Taller II   Python Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
Temario Python Ciencias
Python Mysql, PostgreSql
Python Web, Django,
Lenguaje Go
Python Ciencias
http://www.scipy.org/SciPy
Thumbnails con PIL import os, sys, Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + "-thumbnail.jpg" try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, "JPEG") except IOError: print "no se puede con", infile
https://cirl.berkeley.edu/view/Py4Science
Características deseables de un lenguaje para uso en ciencia. Libre y gratuito.
Fácil de leer.
Fácil de aprender.
Tipo de datos versátiles (alto nivel).
Biblioteca completa (incorporada y disponible externamente).
Suficientemente rápido
Matemática NumPy: Manejo de matrices N-dimensionales.
Funciones algebra lineal
Transformaciones de Fourier
Números aleatorios sofisticados
Herramientas para integrar código C++ y Fortran Matplotlib: “framework para crear gráficos científicos similares a las herramientas provistas por Matlab”.
Chaco: 2-Dimensional Plotting
Interfase: GNUPLOT, R, MATLAB.
t200.py import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_subplot(111) n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75) bincenters = 0.5*(bins[1:]+bins[:-1]) y = mlab.normpdf( bincenters, mu, sigma) l = ax.plot(bincenters, y, 'r--', linewidth=1) ax.set_xlabel('Smarts') ax.set_ylabel('Probability') ax.set_xlim(40, 160) ax.set_ylim(0, 0.03) ax.grid(True) plt.show()
t200.py
from matplotlib import rcParams rcParams['text.usetex']=True rcParams['text.latex.unicode']=True from numpy import arange, cos, pi from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, grid, savefig, show figure(1, figsize=(6,4)) ax = axes([0.1, 0.1, 0.8, 0.7]) t = arange(0.0, 1.0+0.01, 0.01) s = cos(2*2*pi*t)+2 plot(t, s) xlabel(r'\textbf{time (s)}') ylabel(ur'\textit{Velocity (\u00B0/sec)}', fontsize=16) title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", fontsize=16, color='r') grid(True) show() t201.py
t201.py
t202.py #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 1.01, 0.01) s = np.sin(2*2*np.pi*t) plt.fill(t, s*np.exp(-5*t), 'r') plt.grid(True) plt.show()
t202.py
t203.py import matplotlib.pyplot as plt import numpy as np from numpy.random import randn fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with vertical colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1']) fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with horizontal colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal') cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) plt.show()
t203.py
t204.py import numpy as np import matplotlib.pyplot as plt import matplotlib.path as path import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[]) im = ax.imshow(np.random.rand(10,10)) patch = patches.Circle((300,300), radius=100) im.set_clip_path(patch) plt.show()
t204.py
 
Matemática Interfases: GNUPLOT, R, MATLAB: FNUPlot-py, Rpy, PyMAT
http://neopythonic.blogspot.com
Python in the Scientific World * Rapid classification of astronomical time-series data, by Josh Bloom, UCB Astronomy Dept. One of the many tools using Python is GroupThink, which lets random people on the web help classify galaxies (more fun than watching porn :-). * The Hubble Space Telescope team in Baltimore has used Python for 10 years. They showed a tool for removing noise generated by cosmic rays from photos of galaxies. The future James Webb Space Telescope will also be using Python. (Perry Greenfield and Michael Droettboom, of STSCI.) * A $1B commitment by the Indian government to improve education in India includes a project by Prabhu Ramachandran of the Department of Aerospace Engineering at IIT Bombay for Python in Science and Engineering Education in India (see http://fossee.in/).
fperez.org/py4science/2009_guido_ucb/index.html
Python DB
http://sourceforge.net/projects/mysql-python/
01mysql.py #!/usr/local/bin/python #from sets import ImmutableSet import MySQLdb import os, sys db = MySQLdb.connect( host =&quot;localhost&quot;,  user = &quot;root&quot;,  passwd = &quot;123456&quot;,  db = &quot;extdbcat&quot; ) cursor = db.cursor () f = open(&quot;archivo.csv&quot;,&quot;r&quot;) for i in range(1,1050): x = f.readline() f.close() db.close()
http://pymssql.sourceforge.net/
01pymysql.py import pymssql import time import string import unicodedata import codecs conn = pymssql.connect(host='xxx', user='xxx', password='xxx', database='xxxx')  c=conn.cursor() for i in range(1): try: c.execute(&quot;Sentencia&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;\n&quot; print a r1=c.fetchone()
01pymysqlmejorando.py for i in range(1): try: c.execute(&quot;sql&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;\n&quot; print a r1=c.fetchone() except pymssql.DatabaseError, err: print str(err) print &quot;Un error en la sesion de la DB &quot; conn.close() break except pymssql.DatabaseError, err: print str(err) print &quot;Fail&quot; time.sleep(0.2) except: print &quot;Fail&quot; time.sleep(0.2)
http://python.projects.postgresql.org/
Postgresql Conn import datetime  connection = psycopg.connect('dbname=COREIS', 'user=roort')  mark = connection.cursor()  st = 'INSERT INTO ' + table + ' (' + columns + ') VALUES (' + values + ')' mark.execute(st)  connection.commit()
Python Web, Django
http://wiki.python.org/moin/WebProgramming
ServidorWeb.py #!/usr/bin/python from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler).serve_forever()
Otro Ejemplo def handle_request(environment, start_response): start_response('200 OK', [('content-type', 'text/html')]) return ['Hello, World!'] if __name__ == '__main__': from wsgiref import simple_server simple_server.make_server('', 8080, handle_request).serve_forever()
00web.py-01 from wsgiref import util from string import Template # Templates wrapper = Template(&quot;&quot;&quot; <html><head><title>$title</title></head><body> $body </body></html> &quot;&quot;&quot;)
00web.py-02 four_oh_four = Template(&quot;&quot;&quot; <html><body> <h1>404-ed!</h1> La URL <i>$url</i> No fue Encontrada. </body></html>&quot;&quot;&quot;)
00web.py-03 pages = { 'index': { 'title': &quot;Hola COREIS&quot;, 'body':  &quot;&quot;&quot;NUESTRA WEB EN PYTHON <a href=&quot;this_page&quot;>COREIS</a>?&quot;&quot;&quot; }, 'this_page': { 'title': &quot;COREIS&quot;, 'body':  &quot;&quot;&quot;Vamos al coreis. <a href=&quot;http://www.coreislima.org/&quot;>COREIS</a>?&quot;&quot;&quot; } }
00web.py-04 def handle_request(environment, start_response): try: fn = util.shift_path_info(environment) if not fn: fn = 'index' response = wrapper.substitute(**pages[fn]) start_response('200 OK', [('content-type', 'text/html')]) except: start_response('404 Not Found', [('content-type', 'text/html')]) response = four_oh_four.substitute(url=util.request_url(environ)) return [response]
00web.py-05 if __name__ == '__main__': from wsgiref import simple_server print(&quot;Starting server on port 8080...&quot;) try: simple_server.make_server('', 8080, handle_request).serve_forever() except KeyboardInterrupt: print(&quot;Ctrl-C Para Salir...&quot;)
email.py-01 import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os
email.py-02 def sendMail(to, subject, text, files=[],server=&quot;localhost&quot;): assert type(to)==list assert type(files)==list fro = &quot;unimauro@gmail.com&quot; msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', &quot;octet-stream&quot;) part.set_payload( open(file,&quot;rb&quot;).read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=&quot;%s&quot;' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(fro, to, msg.as_string() ) smtp.close() sendMail( [&quot;carlos.cardenas.f@upch.pe&quot;], &quot;hello&quot;,&quot;cheers&quot;, [&quot;usuarios.sql&quot;,&quot;ThekeRS.doc&quot;] )
email02.py-01 import smtplib import mimetypes from email.MIMEText import MIMEText from email.Encoders import encode_base64
email02.py-02 mensaje = MIMEText(&quot;&quot;&quot;Prueba 2 Desde Python&quot;&quot;&quot;) mensaje['From']=&quot;unimauro@gmail.com&quot; mensaje['To']=&quot;carlos.cardenas.f@upch.pe&quot; mensaje['Subject']=&quot;Prueba 2&quot; # Establecemos conexion con el servidor smtp de gmail mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() #mailServer.login(&quot;uio@gmail.com&quot;,&quot;password&quot;) mailServer.login(&quot;unimauro@gmail.com&quot;,&quot;esperanza1504&quot;) # Envio del mensaje mailServer.sendmail(&quot;usuario@gmail.com&quot;, &quot;carlos.cardenas.f@upch.pe&quot;, mensaje.as_string())
 
www.djangoproject.com
 
Models Templates Admin Forms Auth i18n GIS Comments DataBrowse Syndication Sitemaps django-evolution django-registration django-jython django-authopenid django-tagging django-command-extensions google-app-engine-django django-search django-contact-form django-contact-form django-bookmarks django-photologue django-timezones django-profile django-mptt Caching Pinax Satchmo
1. Modelos
# eldemo/elinux/models.py: from django.db import models from datetime import date class Noticia(models.Model):   fecha = models.DateField(   default=date.today)   titulo = models.CharField(max_length=80)   contenido = models.TextField()
class Expositor(models.Model):   nombre = models.CharField(max_length=80,   unique=True)   foto = models.ImageField(   upload_to=&quot;fotos&quot;)   resena = models.TextField(null=True,   blank=True)   invitado = models.BooleanField()
class Charla(models.Model):   titulo = models.CharField(max_length=120,   unique=True)   expositor = models.ForeignKey(Expositor)
¿SQL?
¿SQL? R: Lo genera Django
BEGIN; CREATE TABLE &quot;elinux_noticia&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;titulo&quot; varchar(80) NOT NULL,   &quot;contenido&quot; text NOT NULL ) ; CREATE TABLE &quot;elinux_expositor&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;nombre&quot; varchar(80) NOT NULL UNIQUE,   &quot;foto&quot; varchar(100) NOT NULL,   &quot;resena&quot; text NULL ) ; CREATE TABLE &quot;elinux_charla&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;titulo&quot; varchar(120) NOT NULL UNIQUE,   &quot;expositor_id&quot; integer NOT NULL REFERENCES &quot;elinux_expositor&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED ) ; CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON &quot;elinux_charla&quot; (&quot;expositor_id&quot;); COMMIT;
# Python: class Charla(models.Model):   titulo = models.CharField(max_length=120,   unique=True)   expositor = models.ForeignKey(Expositor) -- SQL: CREATE TABLE &quot;elinux_charla&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;titulo&quot; varchar(120) NOT NULL UNIQUE,   &quot;expositor_id&quot; integer NOT NULL REFERENCES   &quot;elinux_expositor&quot; (&quot;id&quot;)    DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON   &quot;elinux_charla&quot; (&quot;expositor_id&quot;);
Bonus
from django.contrib import admin from elinux.models import Noticia, Expositor,   Charla admin.site.register(Expositor) admin.site.register(Charla) admin.site.register(Noticia)
 
 
 
 
 
 
 
¿Qué es Plone? Sistema de gestión de contenido web Escrito sobre Zope Programado en Python
Características de Plone como CMS Distintos tipos de contenido
Distintas formas de presentar el mismo contenido
Editor HTML WYSIWYG
Flujos de trabajo aplicables al contenido
Herramientas de colaboración
Indexado de texto completo de archivos PDF/OO
Instalación de Plone Descargar Plone desde: http://launchpad.net/plone/3.3/3.3/+download/Plone-3.3-UnifiedInstaller.tgz Ejecutar la instalación: $ tar zxfv Plone-3.3-UnifiedInstaller.tgz $ cd Plone-3.3-UnifiedInstaller/ $ ./install.sh standalone Iniciar el servidor: $ cd $HOME/Plone/zinstance $ ./bin/instance fg Acceder a Plone desde el navegador en: http://localhost:8080/Plone
Instalación de Plone  (para desarrollo) Virtualenv PasteScript ZopeSkel zc.buildout
Requerimientos Editar contenido fácilmente Múltiples usuarios Niveles de acceso Galería de fotos Issue tracker Identidad gráfica Puesta en producción Poi Labs Linux+Apache+Zope
http://www.turbogears.org/
http://code.google.com/appengine
introducción a Google App Engine
Entorno de desarrollo que proporciona: Servidor web
Base de datos (no relacional)
Escalabilidad y balanceo de carga automático
API para autenticar usuarios
Servidor de correo electrónico

Taller II Coreis Python 13112009

  • 1.
    Taller II Python Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
    Thumbnails con PILimport os, sys, Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + &quot;-thumbnail.jpg&quot; try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, &quot;JPEG&quot;) except IOError: print &quot;no se puede con&quot;, infile
  • 9.
  • 10.
    Características deseables deun lenguaje para uso en ciencia. Libre y gratuito.
  • 11.
  • 12.
  • 13.
    Tipo de datosversátiles (alto nivel).
  • 14.
    Biblioteca completa (incorporaday disponible externamente).
  • 15.
  • 16.
    Matemática NumPy: Manejode matrices N-dimensionales.
  • 17.
  • 18.
  • 19.
  • 20.
    Herramientas para integrarcódigo C++ y Fortran Matplotlib: “framework para crear gráficos científicos similares a las herramientas provistas por Matlab”.
  • 21.
  • 22.
  • 23.
    t200.py import numpyas np import matplotlib.pyplot as plt import matplotlib.mlab as mlab mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_subplot(111) n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75) bincenters = 0.5*(bins[1:]+bins[:-1]) y = mlab.normpdf( bincenters, mu, sigma) l = ax.plot(bincenters, y, 'r--', linewidth=1) ax.set_xlabel('Smarts') ax.set_ylabel('Probability') ax.set_xlim(40, 160) ax.set_ylim(0, 0.03) ax.grid(True) plt.show()
  • 24.
  • 25.
    from matplotlib importrcParams rcParams['text.usetex']=True rcParams['text.latex.unicode']=True from numpy import arange, cos, pi from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, grid, savefig, show figure(1, figsize=(6,4)) ax = axes([0.1, 0.1, 0.8, 0.7]) t = arange(0.0, 1.0+0.01, 0.01) s = cos(2*2*pi*t)+2 plot(t, s) xlabel(r'\textbf{time (s)}') ylabel(ur'\textit{Velocity (\u00B0/sec)}', fontsize=16) title(r&quot;\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!&quot;, fontsize=16, color='r') grid(True) show() t201.py
  • 26.
  • 27.
    t202.py #!/usr/bin/env pythonimport numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 1.01, 0.01) s = np.sin(2*2*np.pi*t) plt.fill(t, s*np.exp(-5*t), 'r') plt.grid(True) plt.show()
  • 28.
  • 29.
    t203.py import matplotlib.pyplotas plt import numpy as np from numpy.random import randn fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with vertical colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1']) fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with horizontal colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal') cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) plt.show()
  • 30.
  • 31.
    t204.py import numpyas np import matplotlib.pyplot as plt import matplotlib.path as path import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[]) im = ax.imshow(np.random.rand(10,10)) patch = patches.Circle((300,300), radius=100) im.set_clip_path(patch) plt.show()
  • 32.
  • 33.
  • 34.
    Matemática Interfases: GNUPLOT,R, MATLAB: FNUPlot-py, Rpy, PyMAT
  • 35.
  • 36.
    Python in theScientific World * Rapid classification of astronomical time-series data, by Josh Bloom, UCB Astronomy Dept. One of the many tools using Python is GroupThink, which lets random people on the web help classify galaxies (more fun than watching porn :-). * The Hubble Space Telescope team in Baltimore has used Python for 10 years. They showed a tool for removing noise generated by cosmic rays from photos of galaxies. The future James Webb Space Telescope will also be using Python. (Perry Greenfield and Michael Droettboom, of STSCI.) * A $1B commitment by the Indian government to improve education in India includes a project by Prabhu Ramachandran of the Department of Aerospace Engineering at IIT Bombay for Python in Science and Engineering Education in India (see http://fossee.in/).
  • 37.
  • 38.
  • 39.
  • 40.
    01mysql.py #!/usr/local/bin/python #fromsets import ImmutableSet import MySQLdb import os, sys db = MySQLdb.connect( host =&quot;localhost&quot;, user = &quot;root&quot;, passwd = &quot;123456&quot;, db = &quot;extdbcat&quot; ) cursor = db.cursor () f = open(&quot;archivo.csv&quot;,&quot;r&quot;) for i in range(1,1050): x = f.readline() f.close() db.close()
  • 41.
  • 42.
    01pymysql.py import pymssqlimport time import string import unicodedata import codecs conn = pymssql.connect(host='xxx', user='xxx', password='xxx', database='xxxx') c=conn.cursor() for i in range(1): try: c.execute(&quot;Sentencia&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;\n&quot; print a r1=c.fetchone()
  • 43.
    01pymysqlmejorando.py for iin range(1): try: c.execute(&quot;sql&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;\n&quot; print a r1=c.fetchone() except pymssql.DatabaseError, err: print str(err) print &quot;Un error en la sesion de la DB &quot; conn.close() break except pymssql.DatabaseError, err: print str(err) print &quot;Fail&quot; time.sleep(0.2) except: print &quot;Fail&quot; time.sleep(0.2)
  • 44.
  • 45.
    Postgresql Conn importdatetime connection = psycopg.connect('dbname=COREIS', 'user=roort') mark = connection.cursor() st = 'INSERT INTO ' + table + ' (' + columns + ') VALUES (' + values + ')' mark.execute(st) connection.commit()
  • 46.
  • 47.
  • 48.
    ServidorWeb.py #!/usr/bin/python fromBaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler).serve_forever()
  • 49.
    Otro Ejemplo defhandle_request(environment, start_response): start_response('200 OK', [('content-type', 'text/html')]) return ['Hello, World!'] if __name__ == '__main__': from wsgiref import simple_server simple_server.make_server('', 8080, handle_request).serve_forever()
  • 50.
    00web.py-01 from wsgirefimport util from string import Template # Templates wrapper = Template(&quot;&quot;&quot; <html><head><title>$title</title></head><body> $body </body></html> &quot;&quot;&quot;)
  • 51.
    00web.py-02 four_oh_four =Template(&quot;&quot;&quot; <html><body> <h1>404-ed!</h1> La URL <i>$url</i> No fue Encontrada. </body></html>&quot;&quot;&quot;)
  • 52.
    00web.py-03 pages ={ 'index': { 'title': &quot;Hola COREIS&quot;, 'body': &quot;&quot;&quot;NUESTRA WEB EN PYTHON <a href=&quot;this_page&quot;>COREIS</a>?&quot;&quot;&quot; }, 'this_page': { 'title': &quot;COREIS&quot;, 'body': &quot;&quot;&quot;Vamos al coreis. <a href=&quot;http://www.coreislima.org/&quot;>COREIS</a>?&quot;&quot;&quot; } }
  • 53.
    00web.py-04 def handle_request(environment,start_response): try: fn = util.shift_path_info(environment) if not fn: fn = 'index' response = wrapper.substitute(**pages[fn]) start_response('200 OK', [('content-type', 'text/html')]) except: start_response('404 Not Found', [('content-type', 'text/html')]) response = four_oh_four.substitute(url=util.request_url(environ)) return [response]
  • 54.
    00web.py-05 if __name__== '__main__': from wsgiref import simple_server print(&quot;Starting server on port 8080...&quot;) try: simple_server.make_server('', 8080, handle_request).serve_forever() except KeyboardInterrupt: print(&quot;Ctrl-C Para Salir...&quot;)
  • 55.
    email.py-01 import smtplibfrom email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os
  • 56.
    email.py-02 def sendMail(to,subject, text, files=[],server=&quot;localhost&quot;): assert type(to)==list assert type(files)==list fro = &quot;unimauro@gmail.com&quot; msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', &quot;octet-stream&quot;) part.set_payload( open(file,&quot;rb&quot;).read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=&quot;%s&quot;' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(fro, to, msg.as_string() ) smtp.close() sendMail( [&quot;carlos.cardenas.f@upch.pe&quot;], &quot;hello&quot;,&quot;cheers&quot;, [&quot;usuarios.sql&quot;,&quot;ThekeRS.doc&quot;] )
  • 57.
    email02.py-01 import smtplibimport mimetypes from email.MIMEText import MIMEText from email.Encoders import encode_base64
  • 58.
    email02.py-02 mensaje =MIMEText(&quot;&quot;&quot;Prueba 2 Desde Python&quot;&quot;&quot;) mensaje['From']=&quot;unimauro@gmail.com&quot; mensaje['To']=&quot;carlos.cardenas.f@upch.pe&quot; mensaje['Subject']=&quot;Prueba 2&quot; # Establecemos conexion con el servidor smtp de gmail mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() #mailServer.login(&quot;uio@gmail.com&quot;,&quot;password&quot;) mailServer.login(&quot;unimauro@gmail.com&quot;,&quot;esperanza1504&quot;) # Envio del mensaje mailServer.sendmail(&quot;usuario@gmail.com&quot;, &quot;carlos.cardenas.f@upch.pe&quot;, mensaje.as_string())
  • 59.
  • 60.
  • 61.
  • 62.
    Models Templates AdminForms Auth i18n GIS Comments DataBrowse Syndication Sitemaps django-evolution django-registration django-jython django-authopenid django-tagging django-command-extensions google-app-engine-django django-search django-contact-form django-contact-form django-bookmarks django-photologue django-timezones django-profile django-mptt Caching Pinax Satchmo
  • 63.
  • 64.
    # eldemo/elinux/models.py: fromdjango.db import models from datetime import date class Noticia(models.Model): fecha = models.DateField( default=date.today) titulo = models.CharField(max_length=80) contenido = models.TextField()
  • 65.
    class Expositor(models.Model): nombre = models.CharField(max_length=80, unique=True) foto = models.ImageField( upload_to=&quot;fotos&quot;) resena = models.TextField(null=True, blank=True) invitado = models.BooleanField()
  • 66.
    class Charla(models.Model): titulo = models.CharField(max_length=120, unique=True) expositor = models.ForeignKey(Expositor)
  • 67.
  • 68.
    ¿SQL? R: Logenera Django
  • 69.
    BEGIN; CREATE TABLE&quot;elinux_noticia&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;titulo&quot; varchar(80) NOT NULL, &quot;contenido&quot; text NOT NULL ) ; CREATE TABLE &quot;elinux_expositor&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;nombre&quot; varchar(80) NOT NULL UNIQUE, &quot;foto&quot; varchar(100) NOT NULL, &quot;resena&quot; text NULL ) ; CREATE TABLE &quot;elinux_charla&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;titulo&quot; varchar(120) NOT NULL UNIQUE, &quot;expositor_id&quot; integer NOT NULL REFERENCES &quot;elinux_expositor&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED ) ; CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON &quot;elinux_charla&quot; (&quot;expositor_id&quot;); COMMIT;
  • 70.
    # Python: classCharla(models.Model): titulo = models.CharField(max_length=120, unique=True) expositor = models.ForeignKey(Expositor) -- SQL: CREATE TABLE &quot;elinux_charla&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;titulo&quot; varchar(120) NOT NULL UNIQUE, &quot;expositor_id&quot; integer NOT NULL REFERENCES &quot;elinux_expositor&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON &quot;elinux_charla&quot; (&quot;expositor_id&quot;);
  • 71.
  • 72.
    from django.contrib importadmin from elinux.models import Noticia, Expositor, Charla admin.site.register(Expositor) admin.site.register(Charla) admin.site.register(Noticia)
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
    ¿Qué es Plone?Sistema de gestión de contenido web Escrito sobre Zope Programado en Python
  • 81.
    Características de Plonecomo CMS Distintos tipos de contenido
  • 82.
    Distintas formas depresentar el mismo contenido
  • 83.
  • 84.
    Flujos de trabajoaplicables al contenido
  • 85.
  • 86.
    Indexado de textocompleto de archivos PDF/OO
  • 87.
    Instalación de PloneDescargar Plone desde: http://launchpad.net/plone/3.3/3.3/+download/Plone-3.3-UnifiedInstaller.tgz Ejecutar la instalación: $ tar zxfv Plone-3.3-UnifiedInstaller.tgz $ cd Plone-3.3-UnifiedInstaller/ $ ./install.sh standalone Iniciar el servidor: $ cd $HOME/Plone/zinstance $ ./bin/instance fg Acceder a Plone desde el navegador en: http://localhost:8080/Plone
  • 88.
    Instalación de Plone (para desarrollo) Virtualenv PasteScript ZopeSkel zc.buildout
  • 89.
    Requerimientos Editar contenidofácilmente Múltiples usuarios Niveles de acceso Galería de fotos Issue tracker Identidad gráfica Puesta en producción Poi Labs Linux+Apache+Zope
  • 90.
  • 91.
  • 92.
  • 93.
    Entorno de desarrolloque proporciona: Servidor web
  • 94.
    Base de datos(no relacional)
  • 95.
    Escalabilidad y balanceode carga automático
  • 96.
  • 97.
    Servidor de correoelectrónico
  • 98.
  • 99.
  • 100.
    Es gratis: 500MBen disco y 5 millones de páginas vistas
  • 101.
    1. Registrar unacuenta http://appengine.google.com/
  • 102.
    2. Descargar elSDK http://code.google.com/intl/es/appengine/downloads.html
  • 103.
    Creamos el archivohelloworld.py en dicho directorio con el contenido: print 'Content-Type: text/plain' print '' print 'Hola Mundo!' Editamos el archivo de configuración app.yaml: application: helloworld version: 1 runtime: python api_version: 1 handlers: - url: /.* script: helloworld.py
  • 104.
    Para comprobar quefunciona, arrancamos el servidor, bien con la interfaz gráfica o en la terminal con: dev_appserver.py helloworld Y accedemos a http://localhost:8080 donde nos debería aparecer “Hola Mundo!” en el navegador.
  • 105.
    Permite crear aplicacionesbasadas en CGI de forma fácil y rápida. Editamos el archivo helloworld.py: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hola Mundo con webapp!') application = webapp.WSGIApplication( [('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == &quot;__main__&quot;: main()
  • 106.
    Entramos en http://appengine.google.com y creamos una aplicación (OJO! Luego no se puede borrar). Editamos el archivo app.yaml y cambiamos el nombre de application por el que hemos usado anteriormente. Subimos la aplicación: (nos pedirá usuario y contraseña de nuestra cuenta de Google) appcfg.py update helloworld Podemos comprobar si ha funcionado entrando en http://<tu_aplicacion>.appspot.com
  • 107.
    11. Más EjemplosEjemplos didácticos http://code.google.com/p/google-app-engine-samples/ Ejemplos funcionando http://flickrsearchr.appspot.com/ http://www.cafesurvey.com/ http://www.congregar.com/ http://www.urlmetrix.com/ http://zchat.appspot.com http://www.jumbra.com/
  • 108.
  • 109.
  • 110.
    Lenguaje para Linuxy MacOSX. PARTE I Configuración e Instalación 1. Instalar: sudo apt-get install mercurial sudo apt-get install bison gcc libc6-dev ed make 2. Configurar Variables de Entorno: export GOARCH=386 export GOROOT=/home/administrador/hg/ export GOBIN=/home/administrador/hg/bin 3. Verificar Variables de Entorno env | grep ^GO
  • 111.
    4. Crear CarpetaBin si es se quiere instalar en otra carpeta mkdir bin 5. Agregar la Variable $GOBIN al PATH de Linux export PATH+=:$GOBIN 6. Verificar: echo $PATH 7. Ingresando a la Carpeta de los Fuentes: cd $GOROOT/src 8. Iniciar la Compilación: ./all.bash Verificar Que todo es OK
  • 112.
    PARTE II 1.vim Hola_Coreis_GO.go package main import &quot;fmt&quot; func main() { fmt.Printf(&quot;Hola Somos Coreis, La Singularidad de las Ciencias\n&quot;) }
  • 113.
    2. Compilación /home/administrador/bin/8gHola_Coreis_GO.go /home/administrador/bin/8l Hola_Coreis_GO.8 3. Ejecución: ./8.out
  • 114.
    package main import&quot;os&quot; import &quot;flag&quot; var nFlag = flag.Bool(&quot;n&quot;, false, `no \n`) func main() { ! flag.Parse(); ! s := &quot;&quot;; ! for i := 0; i < flag.NArg(); i++ { ! ! if i > 0 { s += &quot; &quot; } ! ! s += flag.Arg(i) ! } ! if !*nFlag { s += &quot;\n&quot; } ! os.Stdout.WriteString(s); }
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
    Carlos Mauro CárdenasFernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]

Notas del editor

  • #21 Por ejemplo, dos autos del mismo modelo, color, motor, salidos de la misma línea de producción el mismo día no dejan de ser dos autos diferentes, por más que su conjunto de atributos y sus valores sean iguales. La única posibilidad de que dos objetos sean iguales es que sean el mismo objeto.
  • #50 http://www.flickr.com/photos/ryanricketts/2295726918/sizes/o/
  • #58 http://www.flickr.com/photos/twatson/2854156629/sizes/l/