Diferencia entre revisiones de «Usuario:Lmorillas/desarrollo web servidor/python cgi»
De WikiEducator
Línea 45: | Línea 45: | ||
</source> | </source> | ||
|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 | ||
}} | }} |
Revisión de 10:53 18 oct 2013
|
(Cap. 4 de Real Python for the Web, de Michael Herman)
|
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>
#!/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()
|
<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,)
|