Servidor web minimal en Python para recibir archivos

En internet está dando vueltas un comando que sirve para poner en marcha un servidor web “temporal” con Python ejecutable con una sola linea. El cual nos sirve para compartir archivos.

Aqui muestro como usando un método parecido podemos montar un servidor y ademas recibir archivos mediante un formulario. Al ejecutar el programa tendremos el servidor escuchando peticiones, tambien claro, existe una pagina (donde esta el formulario propiamente tal) , este formulario envía un archivo y lo guarda en el directorio donde tenemos el programa. El código (tome un codigo y lo modifique para guardar los archivos enviados):

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 

class MyHandler(BaseHTTPRequestHandler): 

 def do_GET(self):
 try:
 if self.path.endswith(".html"):
 f = open(curdir + sep + self.path)  

 self.send_response(200)
 self.send_header('Content-type',    'text/html')
 self.end_headers()
 self.wfile.write(f.read())
 f.close()
 return
 if self.path.endswith(".esp"):   #our dynamic content
 self.send_response(200)
 self.send_header('Content-type',    'text/html')
 self.end_headers()
 self.wfile.write("hey, today is the" + str(time.localtime()[7]))
 self.wfile.write(" day in the year " + str(time.localtime()[0]))
 return 

 return 

 except IOError:
 self.send_error(404,'File Not Found: %s' % self.path) 

 def do_POST(self):
 global rootnode
 try:
 ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
 if ctype == 'multipart/form-data':
 query=cgi.parse_multipart(self.rfile, pdict)
 self.send_response(301) 

 self.end_headers()
 upfilecontent = query.get('upfile')
 campo_nombre = query.get('nombre') 

 self.wfile.write("<HTML>ENVIO CORRECTO<BR/>");
 self.wfile.write("</HTML>"); 

 f = open ('Archivo_'+campo_nombre[0], "w")
 self.wfile.write(f.write(upfilecontent[0]));
 except :
 pass 

def main():
 try:
 server = HTTPServer(('', 8000), MyHandler)
 print 'Iniciando...'
 print 'Control + C para apagar'
 server.serve_forever()
 except KeyboardInterrupt:
 print 'Apagado por usuario...'
 server.socket.close() 

if __name__ == '__main__':
 main()

Guardamos el codigo como “servidor.py”

Y el codigo del formulario, notar que estamos llamando a la misma maquina indicando el puerto 8000:

Seguir leyendo…

<html>
<body>
 <form enctype="multipart/form-data" action="http://localhost:8000" method="post">
 <p>Nombre: <INPUT type="text" name="nombre" size="30" maxlength="40"/></p>
 <p>File: <input type="file" name="upfile" /></p>
 <p><input type="submit" value="Upload" /></p>
 </form>
</body>
</html>

Para ejecutar el servidor, en un terminal escribimos “./servidor.py”.

Y para acceder a la pagina web donde debemos cargar los archivos debemos escribir en el navegador de internet: “http://direccionip:8000/upload.html” en el caso de haber llamado asi al archivo.

Deje un comentario


NOTA - Puede usar estosHTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>