SlideShare una empresa de Scribd logo
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

Más contenido relacionado

PDF
Pensando funcionalmente
PDF
Programacion en python_2
DOCX
Codigos de programas
ODP
Go python, go
TXT
Lab
PDF
Quasi - Practicas de Programacion en C
PDF
Hacking ético con herramientas Python
ODP
Taller I Coreis Python 10112009
Pensando funcionalmente
Programacion en python_2
Codigos de programas
Go python, go
Lab
Quasi - Practicas de Programacion en C
Hacking ético con herramientas Python
Taller I Coreis Python 10112009

La actualidad más candente (9)

PDF
De 0 A Python En 40 Minutos
PDF
Clase1_Python-CTIC
PDF
Tests en Java con Groovy y Spock
PDF
02 pythonenpocospasosejercicios.ipynb colaboratory
PDF
Introduccion a python 3
DOCX
bibliotecas c++
PDF
PostgreSQL À la Debian
PDF
Introduccion a Python. Clase 1
De 0 A Python En 40 Minutos
Clase1_Python-CTIC
Tests en Java con Groovy y Spock
02 pythonenpocospasosejercicios.ipynb colaboratory
Introduccion a python 3
bibliotecas c++
PostgreSQL À la Debian
Introduccion a Python. Clase 1
Publicidad

Similar a Taller II Coreis Python 13112009 (20)

ODP
Asegúr@IT II - Seguridad en Web
ODP
Python Multiuso
PPT
Modelo Simulado
ODP
Node.js - Eventos para Todos
PPT
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
ODP
Curso de Django | Django Course
DOCX
Informe minishell
PPT
Python Tutorial Presentation
PPT
Especialista Web J9 Php
ODP
Java 7- Java Day Guatemala
PDF
Introduccion a Python
DOC
Unidad16 Codigof1
DOC
Ejemplos Importantisimo
PDF
ODP
Introducción a Python
DOCX
Codigos de programas
DOCX
Codigos de programas
PPT
Hebras En Accion
PDF
Creacion de proyecto_en_netbeans
DOCX
Asegúr@IT II - Seguridad en Web
Python Multiuso
Modelo Simulado
Node.js - Eventos para Todos
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
Curso de Django | Django Course
Informe minishell
Python Tutorial Presentation
Especialista Web J9 Php
Java 7- Java Day Guatemala
Introduccion a Python
Unidad16 Codigof1
Ejemplos Importantisimo
Introducción a Python
Codigos de programas
Codigos de programas
Hebras En Accion
Creacion de proyecto_en_netbeans
Publicidad

Más de Carlos Cardenas Fernandez (20)

PDF
PDF
Data_Science_Machine_Learning_Base.pdf
PPTX
Inteligencia artificial: Estado del Arte
PPTX
Inteligencia artificial: Transformando Mercados
ODP
Google Summer of Code 2018 :: Envuelvete
PPT
Impacto del software libre en la eduacion
PPT
Sustentacion de Tesis Ingenieria de Usabilidad
PDF
St285 U09 II Clase 11/09/2009
ODP
Clase de Aplicación de Negocios Electrónicos St295 U09 Ii01
PPT
Python Tercera Sesion de Clases
ODP
Python Segunda Sesion de Clases
ODP
Integración de Pymes
ODP
ST289U2009I Clase29052009
PDF
Portales Con Adsense
ODP
ST289U2009I Clase22052009
ODP
UNET Integrando a las Pymes
PDF
PDF
PLATAFORMA PARA PYMES ASOCIADAS
PPT
Sistemas Electricos Y Electronicos 01
ODP
Data_Science_Machine_Learning_Base.pdf
Inteligencia artificial: Estado del Arte
Inteligencia artificial: Transformando Mercados
Google Summer of Code 2018 :: Envuelvete
Impacto del software libre en la eduacion
Sustentacion de Tesis Ingenieria de Usabilidad
St285 U09 II Clase 11/09/2009
Clase de Aplicación de Negocios Electrónicos St295 U09 Ii01
Python Tercera Sesion de Clases
Python Segunda Sesion de Clases
Integración de Pymes
ST289U2009I Clase29052009
Portales Con Adsense
ST289U2009I Clase22052009
UNET Integrando a las Pymes
PLATAFORMA PARA PYMES ASOCIADAS
Sistemas Electricos Y Electronicos 01

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]
  • 8. Thumbnails con PIL import 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
  • 10. Características deseables de un lenguaje para uso en ciencia. Libre y gratuito.
  • 13. Tipo de datos versátiles (alto nivel).
  • 14. Biblioteca completa (incorporada y disponible externamente).
  • 16. Matemática NumPy: Manejo de matrices N-dimensionales.
  • 20. Herramientas para integrar código C++ y Fortran Matplotlib: “framework para crear gráficos científicos similares a las herramientas provistas por Matlab”.
  • 23. 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()
  • 25. 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&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
  • 27. 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()
  • 29. 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()
  • 31. 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()
  • 33.  
  • 34. Matemática Interfases: GNUPLOT, R, MATLAB: FNUPlot-py, Rpy, PyMAT
  • 36. 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/).
  • 40. 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()
  • 42. 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()
  • 43. 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)
  • 45. 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()
  • 48. ServidorWeb.py #!/usr/bin/python from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler).serve_forever()
  • 49. 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()
  • 50. 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;)
  • 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 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
  • 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 smtplib import 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.  
  • 61.  
  • 62. 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
  • 64. # 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()
  • 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)
  • 68. ¿SQL? R: Lo genera 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: 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;);
  • 71. Bonus
  • 72. from django.contrib import admin 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 Plone como CMS Distintos tipos de contenido
  • 82. Distintas formas de presentar el mismo contenido
  • 84. Flujos de trabajo aplicables al contenido
  • 86. Indexado de texto completo de archivos PDF/OO
  • 87. 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
  • 88. Instalación de Plone (para desarrollo) Virtualenv PasteScript ZopeSkel zc.buildout
  • 89. 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
  • 93. Entorno de desarrollo que proporciona: Servidor web
  • 94. Base de datos (no relacional)
  • 95. Escalabilidad y balanceo de carga automático
  • 97. Servidor de correo electrónico
  • 100. Es gratis: 500MB en disco y 5 millones de páginas vistas
  • 101. 1. Registrar una cuenta http://appengine.google.com/
  • 102. 2. Descargar el SDK http://code.google.com/intl/es/appengine/downloads.html
  • 103. Creamos el archivo helloworld.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 que funciona, 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 aplicaciones basadas 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 Ejemplos Ejemplos 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/
  • 110. Lenguaje para Linux y 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 Carpeta Bin 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/8g Hola_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); }
  • 117.  
  • 118.  
  • 123. Carlos Mauro Cárdenas Ferná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/