Created
April 30, 2019 15:02
-
-
Save nisevi/23b83732a9b5905c61e7636272e4e545 to your computer and use it in GitHub Desktop.
TPL 5 - EJ14 - World Wide Web - HTTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import BaseHTTPServer | |
HOST_NAME = 'localhost' | |
PORT = 8000 | |
def detectar_so(user_agent): | |
# Ver listados en http://www.useragentstring.com/pages/useragentstring.php | |
if 'Linux' in user_agent: | |
return 'Veo que Ud. esta usando Linux como S.O.' | |
elif 'Windows' in user_agent: | |
return 'Veo que Ud. esta usando Windows como S.O.' | |
else: | |
return 'No conozco su S.O.' | |
def get_pagina_ok(): | |
""" Función que dvuelve la página de exito de ejemplo """ | |
# Como alternativa podría abrirse un archivo del disco, leerlo y devolverlo | |
# como cadena de texto. | |
return ('<html><head><title>Pagina HTML de ejemplo</title>' | |
'</head><body><p>Esta es una prueba, con texto en <b>negrita</b>,' | |
'<i>cursiva</i> e incluso una imagen externa:</p>' | |
'<img src="http://www.labredes.unlu.edu.ar/themes/glossyblue/images' | |
'/header-bg.jpg" />') | |
class Handler(BaseHTTPServer.BaseHTTPRequestHandler): | |
def do_GET(server): | |
"""Respondo a una petición de tipo GET""" | |
# Imprimo los encabezados por consola | |
print '-' * 80 | |
print server.command, server.path, server.request_version | |
print server.headers | |
# Devuelvo la respuesta | |
if server.path.startswith('/ir_a/'): | |
ir_a = server.path.split('/')[-1] | |
server.send_response(302) | |
server.send_header('Location', 'http://' + ir_a) | |
server.end_headers() | |
elif server.path.startswith('/no_existe'): | |
server.send_response(404) | |
server.send_header('Content-Type', 'text/plain') | |
server.end_headers() | |
server.wfile.write('Pagina no encontrada') | |
else: | |
server.send_response(200) | |
server.send_header('Content-Type', 'text/html') | |
server.end_headers() | |
server.wfile.write(get_pagina_ok()) | |
server.wfile.write('<p>' + detectar_so(server.headers['User-Agent'])) | |
server.wfile.write('</p></body></html>') | |
def log_message(*args): | |
""" Deshabilito la salida por defecto del servidor """ | |
pass | |
if __name__ == '__main__': | |
http_server = BaseHTTPServer.HTTPServer((HOST_NAME, PORT), Handler) | |
print 'Ejecutando Server HTTP - %s:%s' % (HOST_NAME, PORT) | |
print 'Presione Ctrl+C para detener...' | |
try: | |
http_server.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
http_server.server_close() | |
print 'Deteniendo Server HTTP - %s:%s' % (HOST_NAME, PORT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment