Diferencia entre revisiones de «Usuario:Lmorillas/desarrollo web servidor/python cgi»

De WikiEducator
Saltar a: navegación, buscar
 
(4 revisiones intermedias por el mismo usuario no mostrado)
Línea 4: Línea 4:
 
{{Objetivo|
 
{{Objetivo|
 
* '''Especificación:''' http://www.ietf.org/rfc/rfc3875.txt
 
* '''Especificación:''' http://www.ietf.org/rfc/rfc3875.txt
* '''Librería python:''' http://docs.python.org/2/library/cgi.html
+
* '''Librería Python:''' http://docs.python.org/2/library/cgi.html
* '''Un tutorial:''' http://www.tutorialspoint.com/python/python_cgi_programming.htm
+
* '''Webservers con Python:''' http://docs.python.org/2/howto/webservers.html#common-gateway-interface
 +
* '''Tutoriales:'''
 +
** http://www.tutorialspoint.com/python/python_cgi_programming.htm
 +
** http://webpython.codepoint.net/cgi_tutorial
 +
* '''CGI con Apache:''' http://httpd.apache.org/docs/2.2/howto/cgi.html
 +
 
 
|Title= Common Gateway Interface
 
|Title= Common Gateway Interface
 
}}
 
}}
Línea 11: Línea 16:
 
{{Actividad|
 
{{Actividad|
 
* http://moodle.cpilosenlaces.com/file.php/266/python/intro_prog_servidor.pdf
 
* http://moodle.cpilosenlaces.com/file.php/266/python/intro_prog_servidor.pdf
}}
+
(Cap. 4 de ''Real Python for the Web'', de Michael Herman)}}
  
 
{{Tip|
 
{{Tip|
Línea 41: Línea 46:
 
|Title=Configuración del servidor
 
|Title=Configuración del servidor
 
}}
 
}}
 +
 +
{{Conocimiento previo|
 +
<source lang="html4strict">
 +
  <form enctype="multipart/form-data"
 +
                    action="save_file.py" method="post">
 +
  <p>File: <input type="file" name="filename" /></p>
 +
  <p><input type="submit" value="Upload" /></p>
 +
  </form>
 +
</source>
 +
<source lang="python">
 +
#!/usr/bin/python
 +
 +
import cgi, os
 +
import cgitb; cgitb.enable()
 +
 +
form = cgi.FieldStorage()
 +
 +
# Get filename here.
 +
fileitem = form['filename']
 +
 +
# Test if the file was uploaded
 +
if fileitem.filename:
 +
  # strip leading path from file name to avoid
 +
  # directory traversal attacks
 +
  fn = os.path.basename(fileitem.filename)
 +
  open('/tmp/' + fn, 'wb').write(fileitem.file.read())
 +
 +
  message = 'The file "' + fn + '" was uploaded successfully'
 +
 
 +
else:
 +
  message = 'No file was uploaded'
 +
 
 +
print """\
 +
Content-Type: text/html\n
 +
<html>
 +
<body>
 +
  <p>%s</p>
 +
</body>
 +
</html>
 +
""" % (message,)
 +
</source>
 +
|Title=Subir un archivo
 +
}}
 +
 +
{{Conocimiento previo|
 +
<source lang="python">
 +
#!/usr/bin/env python
 +
 +
# HTTP Header
 +
print 'Content-Type:application/octet-stream; name="FileName"\n'
 +
print 'Content-Disposition: attachment; filename="FileName"\n\n'
 +
 +
# Actual File Content will go hear.
 +
fo = open("foo.txt", "rb")
 +
 +
str = fo.read();
 +
print str
 +
 +
# Close opend file
 +
fo.close()
 +
</source>
 +
|Title=Lanzar descarga de archivo
 +
}}
 +
 +
{{Tip|''CGI scripts run by the CGIHTTPRequestHandler class cannot execute redirects (HTTP code 302), because code 200 (script output follows) is sent prior to execution of the CGI script. This pre-empts the status code.'' http://docs.python.org/2/library/cgihttpserver.html}}

Última revisión de 18:20 22 oct 2013





Icon activity.jpg

Actividad

(Cap. 4 de Real Python for the Web, de Michael Herman)




Icon present.gif
Tip:
  • Para los ejercicios usaremos CGIHTTPServer
 python -m CGIHTTPServer
  • Los programas cgi estarán en un subdirectorio cgi-bin
  • Esos programas tienen que estar identificados como programas python
 #!/usr/bin/env python
  • Tienen que tener permisos de ejecución
 $ chmos +x <programa_cgi.py>




Icon activity.jpg

Configuración del servidor

#!/usr/bin/env python
 
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()  ## Para mostrar errores CGI
 
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = [""]  ## En qué directorios puede haber programas CGI
 
httpd = server(server_address, handler)
httpd.serve_forever()






Icon preknowledge.gif

Subir un archivo

   <form enctype="multipart/form-data" 
                     action="save_file.py" method="post">
   <p>File: <input type="file" name="filename" /></p>
   <p><input type="submit" value="Upload" /></p>
   </form>
#!/usr/bin/python
 
import cgi, os
import cgitb; cgitb.enable()
 
form = cgi.FieldStorage()
 
# Get filename here.
fileitem = form['filename']
 
# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid 
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())
 
   message = 'The file "' + fn + '" was uploaded successfully'
 
else:
   message = 'No file was uploaded'
 
print """\
Content-Type: text/html\n
<html>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,)





Icon preknowledge.gif

Lanzar descarga de archivo

#!/usr/bin/env python
 
# HTTP Header
print 'Content-Type:application/octet-stream; name="FileName"\n'
print 'Content-Disposition: attachment; filename="FileName"\n\n'
 
# Actual File Content will go hear.
fo = open("foo.txt", "rb")
 
str = fo.read();
print str
 
# Close opend file
fo.close()



Icon present.gif
Tip: CGI scripts run by the CGIHTTPRequestHandler class cannot execute redirects (HTTP code 302), because code 200 (script output follows) is sent prior to execution of the CGI script. This pre-empts the status code. http://docs.python.org/2/library/cgihttpserver.html