El documento presenta información sobre un taller de Python. Incluye los siguientes temas: ciencias con Python usando bibliotecas como NumPy, Matplotlib y Chaco; bases de datos con Python usando MySQL, PostgreSQL y SQLite; desarrollo web con Python y Django; y correo electrónico con Python. También menciona brevemente al lenguaje Go y provee código de ejemplo para varios de los temas.
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/).
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("Sentencia") result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+" , "+r1[1]+" ,student"+"" print a r1=c.fetchone()
43. 01pymysqlmejorando.py for i in range(1): try: c.execute("sql") result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+" , "+r1[1]+" ,student"+"" print a r1=c.fetchone() except pymssql.DatabaseError, err: print str(err) print "Un error en la sesion de la DB " conn.close() break except pymssql.DatabaseError, err: print str(err) print "Fail" time.sleep(0.2) except: print "Fail" time.sleep(0.2)
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(""" <html><head><title>$title</title></head><body> $body </body></html> """)
51. 00web.py-02 four_oh_four = Template(""" <html><body> <h1>404-ed!</h1> La URL <i>$url</i> No fue Encontrada. </body></html>""")
52. 00web.py-03 pages = { 'index': { 'title': "Hola COREIS", 'body': """NUESTRA WEB EN PYTHON <a href="this_page">COREIS</a>?""" }, 'this_page': { 'title': "COREIS", 'body': """Vamos al coreis. <a href="http://www.coreislima.org/">COREIS</a>?""" } }
54. 00web.py-05 if __name__ == '__main__': from wsgiref import simple_server print("Starting server on port 8080...") try: simple_server.make_server('', 8080, handle_request).serve_forever() except KeyboardInterrupt: print("Ctrl-C Para Salir...")
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
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="fotos") 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)
69. BEGIN; CREATE TABLE "elinux_noticia" ( "id" serial NOT NULL PRIMARY KEY, "titulo" varchar(80) NOT NULL, "contenido" text NOT NULL ) ; CREATE TABLE "elinux_expositor" ( "id" serial NOT NULL PRIMARY KEY, "nombre" varchar(80) NOT NULL UNIQUE, "foto" varchar(100) NOT NULL, "resena" text NULL ) ; CREATE TABLE "elinux_charla" ( "id" serial NOT NULL PRIMARY KEY, "titulo" varchar(120) NOT NULL UNIQUE, "expositor_id" integer NOT NULL REFERENCES "elinux_expositor" ("id") DEFERRABLE INITIALLY DEFERRED ) ; CREATE INDEX "elinux_charla_expositor_id" ON "elinux_charla" ("expositor_id"); COMMIT;
70. # Python: class Charla(models.Model): titulo = models.CharField(max_length=120, unique=True) expositor = models.ForeignKey(Expositor) -- SQL: CREATE TABLE "elinux_charla" ( "id" serial NOT NULL PRIMARY KEY, "titulo" varchar(120) NOT NULL UNIQUE, "expositor_id" integer NOT NULL REFERENCES "elinux_expositor" ("id") DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX "elinux_charla_expositor_id" ON "elinux_charla" ("expositor_id");
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
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__ == "__main__": 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
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 "fmt" func main() { fmt.Printf("Hola Somos Coreis, La Singularidad de las Ciencias") }
123. Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
Notas del editor
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.