4.4. Respuesta Iterable¶
Si el último script print_environment.py funcionó, cambie la línea de retorno:
return [response_body]
por la siguiente linea:
return response_body
Importante
Luego ejecútalo el script de nuevo, el servidor estará atendiendo peticiones en la dirección en http://localhost:8051
En una máquina más antigua es posible notar que es más lenta. Lo que sucede es que el servidor iteraba sobre la cadena y enviaba un solo byte a la vez al cliente. Así que no olvide envolver la respuesta en un mejor rendimiento iterable como una lista.
Si el iterable produce más de una cadena, la longitud del cuerpo de la response será la suma de todas las longitudes de la cadena, como en este script:
#!/usr/bin/env python
"""
Python's bundled WSGI server
Source code taken and improvements from the
"WSGI Tutorial" by Clodoaldo Pinto Neto at
http://wsgi.tutorial.codepoint.net/response-iterable
"""
from wsgiref.simple_server import make_server
def application(environ, start_response):
# Sorting and stringifying the environment key, value pairs
response_body = [f"{key}: {value}" for key, value in sorted(environ.items())]
response_body = "\n".join(response_body)
# Adding strings to the response body
response_body = [
"The Beggining\n",
"*" * 30 + "\n",
response_body,
"\n" + "*" * 30,
"\nThe End",
]
# So the content-lenght is the sum of all string's lengths
content_length = sum(len(s) for s in response_body)
status = "200 OK"
response_headers = [
("Content-Type", "text/plain"),
("Content-Length", str(content_length)),
]
start_response(status, response_headers)
return response_body
# Instantiate the server
httpd = make_server(
"localhost", # The host name
8080, # A port number where to wait for the request
application, # The application object name, in this case a function
)
# Wait for a single request, serve it and quit
httpd.handle_request()
Importante
Usted puede descargar el código usado en esta sección haciendo clic
aquí
.
Truco
Para ejecutar el código response_iterable.py
, abra una consola de
comando, acceda al directorio donde se encuentra el mismo, y ejecute el siguiente
comando:
python3 response_iterable.py
El servidor estará atendiendo peticiones en la dirección en http://localhost:8051
Ver también
Consulte la sección de lecturas suplementarias del entrenamiento para ampliar su conocimiento en esta temática.
¿Cómo puedo ayudar?
¡Mi soporte está aquí para ayudar!
Mi horario de oficina es de lunes a sábado, de 9 AM a 5 PM. GMT-4 - Caracas, Venezuela.
La hora aquí es actualmente 7:35 PM GMT-4.
Mi objetivo es responder a todos los mensajes dentro de un día hábil.