async def handle_echo(reader, writer): global path global size data = await reader.read(size) message = data.decode() #consulta GET addr = writer.get_extra_info('peername') await log_handle(addr, path) solicitud = urlparse(message) pedido = solicitud.path.split()[1] if (pedido == '/') or (pedido == '/index.html'): body = fc.Index(path) extension = 'html' header = bytearray( "HTTP/1.1 200 OK\r\n Content-Type:" + extension + " \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') #print(body) #respuesta = header + body #self.request.sendall(respuesta) else: tomarextension = pedido.split('.')[1] extension = fc.procesar_mimetype(tomarextension) print(extension) solicitud = path + pedido fd = fc.abrir_archivo(solicitud) if os.path.isfile(fd) == False: fd2 = fc.abrir_archivo(directorio + "error.html") body = os.read(fd2, size) #body = "<html><head><meta<title>Mi pagina de prueba</title></head><body><p>Hola Mundo todo bien</p></body></html>" header = bytearray( "HTTP/1.1 404 error\r\n Content-Type:" + extension + " \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') if os.path.isfile(solicitud) == True: body = os.read(fd, os.path.getsize(solicitud)) os.close(fd) header = bytearray( "HTTP/1.1 200 OK\r\n Content-Type:" + extension + " \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') respuesta = header + body #self.request.sendall(respuesta) # addr = writer.get_extra_info('peername') # print("Received %r from %r" % (message, addr)) # print("Send: %r" % message) writer.write(respuesta) await writer.drain()
def menu(): archivo_clientes = funciones.clientes_archivo() funciones.abrir_archivo(archivo_clientes) archivo_viaticos = funciones.viaticos_archivo() funciones.abrir_archivo(archivo_viaticos) if funciones.comprobacion_clientes( archivo_clientes) == False or funciones.comprobacion_viajes( archivo_viaticos) == False: print("No se puede seguir con la ejecución...") exit() while True: tipo_log = "Menú" funciones.escribir_log(tipo_log) opcion = input( "*** MENU ***\n1- Buscar cliente\n2- Busqueda de usuarios por Empresa\n3- Total de viaticos por Empresa\n4- Viajes por Cliente\n5- Salir\n" ) # Opcion 1: Buscar nombre de cliente if opcion == "1": funciones.busqueda(archivo_clientes, archivo_viaticos, 1) # Opcion 2: Buscar Usuario por Empresa elif opcion == "2": funciones.busqueda(archivo_clientes, archivo_viaticos, 2) # Opcion 3: Total viaticos por Empresa elif opcion == "3": funciones.busqueda(archivo_clientes, archivo_viaticos, 3) # Ocion 4: Total viaticos por Cliente elif opcion == "4": funciones.busqueda(archivo_clientes, archivo_viaticos, 4) elif opcion == "5": tipo_log = "Salir" funciones.escribir_log(tipo_log) exit()
async def log_handle(addr, path): nombre = path + "login" date = time.strftime("%c") login = "******" + str( addr) + " la fecha y hora: " + str(date) print(login) fd = fc.abrir_archivo(nombre) if os.path.isfile(fd) == True: fd2 = open(nombre, 'a') fd2.write(login) else: fp = open(nombre, 'w+') fp.write(login) os.close(fd)
def handle(self): dic = { "text": "text/plain", "jpg": "image/jpeg", "ppm": "image/x-portable-pixmap", "html": "text/html", "pdf": "application/pdf" } directorio = self.server.directorio tamano = self.server.tamano self.data = self.request.recv(1024) encabezado = self.data.decode().splitlines()[0] if encabezado.split()[1] == False: archivo = encabezado.split()[0] archivo = encabezado.split()[1] #extension = archivo.split('.')[1] #print(extension) if archivo == '/': archivo = '/index.html' extension = 'html' else: #archivo = encabezado.split()[1] extension = archivo.split('.')[1] #if os.path.isfile(archivo)== False: # archivo = './400error.html' solicitud = directorio + archivo print(solicitud) fd = fc.abrir_archivo(solicitud) if os.path.isfile(fd) == False: header = bytearray( "HTTP/1.1 404 error\r\n Content-Type:" + dic[extension] + " \r\nContent-length: \r\n\r\n", 'utf8') body = "<html><head><meta<title>Mi pagina de prueba</title></head><body><p>Hola Mundo todo bien</p></body></html>" print(dic[extension]) header = bytearray( "HTTP/1.1 200 OK\r\n Content-Type:" + dic[extension] + " \r\nContent-length: \r\n\r\n", 'utf8') body = os.read(fd, tamano) respuesta = header + body self.request.sendall(respuesta)
import ventanas import funciones import collections #fuente: https://ourworldindata.org/life-expectancy header, lista = funciones.abrir_archivo('files', 'life-expectancy.csv') lista = list( map( lambda y: [y[0], float(y[3])], filter(lambda x: x[2] == '2019' and not funciones.continente(x[0]), lista))) c = collections.Counter mayor_exp = {} for elem in lista: mayor_exp[elem[0]] = elem[1] mayor_exp = c(mayor_exp).most_common( 20) #los 20 estados que mayor expectativa de vida tienen en 2019 dic_mayor_exp = dict(mayor_exp) funciones.crear_json('files', 'expectativa.txt', dic_mayor_exp) # fuente: https://www.kaggle.com/eliasdabbas/emoji-data-descriptions-codepoints header, emojis = funciones.abrir_archivo('files', 'emoji_df.csv') emojis = list( map( lambda y: [y[0], y[1]], filter(
def handle(self): directorio = self.server.directorio tamano = self.server.tamano self.data = self.request.recv(tamano) hilos = self.server.hilos encabezado = self.data.decode().splitlines()[0] if encabezado.split()[1] == False: archivo = encabezado.split()[0] print(archivo) archivo = encabezado.split()[1] print(archivo) esunfiltro = archivo.find("?") print(esunfiltro) try: if esunfiltro != -1: dato = archivo.find("ppm") if dato > 0: image = archivo.split('&') name = image[0].split('=') color = image[1].split('=') intensity = image[2].split('=') intensidad = intensity[1] imagen = name[1] imagen = imagen[4:] filtro = color[1] print("HERE: ", imagen, filtro, intensidad) estado = fc.aplicarfiltro(imagen, filtro, intensidad, tamano, directorio, hilos) if estado == 0: #TODO: debe haber solo una pagina de exito en la raiz, no en cada uno de las rutas fd2 = fc.abrir_archivo(directorio + "exito.html") body = os.read(fd2, tamano) header = bytearray( "HTTP/1.1 200 OK\r\n Content-Type:html \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') else: #TODO: debe haber solo una pagina de error en la raiz, no en cada uno de las rutas fd2 = fc.abrir_archivo(directorio + "error.html") body = os.read(fd2, tamano) header = bytearray( "HTTP/1.1 404 error\r\n Content-Type:html \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') respuesta = header + body self.request.sendall(respuesta) elif (archivo == '/') or (archivo == '/index.html'): body = fc.index(directorio) header = bytearray( "HTTP/1.1 200 OK\r\n Content-Type: html \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') print(body) respuesta = header + body self.request.sendall(respuesta) else: tomarextension = archivo.split('.')[1] extension = fc.procesar_mimetype(tomarextension) print(extension) solicitud = directorio + archivo fd = fc.abrir_archivo(solicitud) if os.path.isfile(fd) == False: fd2 = fc.abrir_archivo(directorio + "error.html") body = os.read(fd2, tamano) header = bytearray( "HTTP/1.1 404 error\r\n Content-Type:" + extension + " \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') if os.path.isfile(solicitud) == True: body = os.read(fd, os.path.getsize(solicitud)) os.close(fd) header = bytearray( "HTTP/1.1 200 OK\r\n Content-Type:" + extension + " \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') respuesta = header + body self.request.sendall(respuesta) except (Exception): fd3 = fc.abrir_archivo("error.html") body = os.read(fd3, tamano) header = bytearray( "HTTP/1.1 404 error\r\n Content-Type:html \r\nContent-length:" + str(len(body)) + " \r\n\r\n", 'utf8') respuesta = header + body self.request.sendall(respuesta)
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "f:n:hp:", ["archivo=", "bloque=", "nro="]) archivo = None bloque = None nro = None for o, a in opts: if o == "-f": archivo = a elif o == "-n": bloque = int(a) elif o == "-p": nro = int(a) elif o == "-h": print 'Ejemplo modo de uso: \n ./tp1.py -f <archivo> -n <tamaño_bloque> -p <cant hijos> \n ./tp1.py -f /etc/services -n 1024 -p 3' sys.exit(2) else: assert False, "option no válida" procesos = [] mq = multiprocessing.Queue() lock = multiprocessing.Lock() cant = multiprocessing.Value('i', 0) #Creamos n procesos for h in range(0, nro): h = multiprocessing.Process(target=funciones.leer, args=( mq, cant, lock, )) procesos.append(h) h.start() with funciones.abrir_archivo(archivo) as file: leido = file.read(bloque) while leido: mq.put(leido) leido = file.read(bloque) file.close() #Le indicamos a los procesos que ya terminamos de poner elementos en la cola for i in procesos: mq.put("DONE") #Terminamos los procesos for h in procesos: h.join() print '\npalabras totales: ', cant.value except getopt.GetoptError as err: print(err) sys.exit(2) except OSError: print 'el archivo indicado no existe' sys.exit(2)