4.4. Respuesta Iterable

Si el último script wsgi_print_environment.py funcionó, cambie la línea de retorno:

return [response_body.encode("utf-8")]

por la siguiente linea:

return response_body.encode("utf-8")

Importante

Luego ejecútalo el script de nuevo, el servidor estará atendiendo peticiones en la dirección en http://localhost:8080

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:

"""Python's bundled WSGI server

Source code taken and improvements from the
"WSGI Tutorial" by Clodoaldo Pinto Neto at
https://wsgi.tutorial.codepoint.net/response-iterable
"""

# Server IP
HOST_NAME = "localhost"
# Server port
PORT_NUMBER = 8080
# HTTP Status
STATUS = "200 OK"


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 Beginning\n",
        "*" * 30 + "\n",
        response_body,
        "\n" + "*" * 30,
        "\nThe End",
    ]
    # So the content-length is the sum of all string's lengths
    content_length = sum(len(s) for s in response_body)
    # HTTP Headers
    RESPONSE_HEADERS = [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(content_length)),
    ]
    # Start the response
    start_response(STATUS, RESPONSE_HEADERS)
    return [s.encode("utf-8") for s in response_body]


server = None
try:
    from wsgiref.simple_server import make_server

    # Instantiate the server
    server = make_server(
        HOST_NAME,  # The host name
        PORT_NUMBER,  # A port number where to wait for the request
        application,  # The application object name, in this case a function
    )
    print(
        f" WSGI Server running on http://{HOST_NAME}:{PORT_NUMBER}/ use <Ctrl-C> to stop."
    )
    # Server serve forever
    server.serve_forever()
    # Wait for a single request, serve it and quit
    server.handle_request()
except KeyboardInterrupt:
    print(" <Ctrl-C> entered, stopping WSGI Server...")
    if server:
        # Close the server
        server.socket.close()

Importante

Usted puede descargar el código usado en esta sección haciendo clic en el siguiente enlace:

Truco

Para ejecutar el código wsgi_response_iterable.py, abra una consola de comando, acceda al directorio donde se encuentra el mismo, y ejecute el siguiente comando:

python3 wsgi_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. UTM - Madrid, España.

La hora aquí es actualmente 7:35 PM UTM.

Mi objetivo es responder a todos los mensajes dentro de un día hábil.

Contrata mi increíble soporte profesional