4.2. Hello World en WSGI

El objeto de esta sección es hacer un demostración local de Hello World en WSGI.

4.2.1. Request GET

En pocas palabras, una aplicación compatible con WSGI debe proporcionar una (función, clase) invocable que acepte un diccionario environ y una función start_response.

Para una comparación familiar de PHP, puede pensar en el diccionario environ como una combinación de $_SERVER, $_GET y $_POST, con procesamiento adicional requerido. Se espera que este invocable invoque la función start_response con el código de respuesta/datos de encabezado deseados, y luego devuelva un byte iterable con el cuerpo de la respuesta.

"""Source code taken and improvements from the article
"Understanding Python WSGI with Examples" by Edd Mann at
https://eddmann.com/posts/understanding-python-wsgi-with-examples/
"""

# Server IP
HOST_NAME = "127.0.0.1"
# Server port
PORT_NUMBER = 8080
# HTTP Status
STATUS = "200 OK"
# HTTP Headers
HEADERS = [("Content-Type", "text/html")]


def application(environ, start_response):
    # Start the response
    start_response(STATUS, HEADERS)
    return [b"Hello, world!"]


def run():
    """Run WSGI Server"""
    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()
    except KeyboardInterrupt:
        print(" <Ctrl-C> entered, stopping WSGI Server...")
        if server:
            # Close the server
            server.socket.close()


if __name__ == "__main__":
    """Starting WSGI server"""
    run()
else:
    print(
        "This script should be run directly and not imported as a module.\n"
        "Please execute it using 'python wsgi_hello_world_get_request.py'."
    )

Truco

Para ejecutar el código wsgi_hello_world_get_request.py y wsgi_hello_world_post_request.py, abra una consola de comando, acceda al directorio donde se encuentra ambos programas:

proyectos/
└── wsgi/
    └── wsgi_hello_world_get_request.py

Si tiene la estructura de archivo previa, entonces ejecute el siguiente comando:

python3 wsgi_hello_world_get_request.py

De esta forma puede una aplicación web WSGI simple que maneja una petición GET .


4.2.2. Request POST

Ahora que esta familiarizado con la estructura básica de una aplicación compatible con WSGI, ahora podemos experimentar con un ejemplo más práctico. A continuación, proporcionamos al cliente un formulario simple que publica un campo llamado name proporcionado para que la aplicación lo salude en consecuencia.

"""Source code taken and improvements from the article
"Understanding Python WSGI with Examples" by Edd Mann at
https://eddmann.com/posts/understanding-python-wsgi-with-examples/
"""

from urllib.parse import parse_qs

# Server IP
HOST_NAME = "127.0.0.1"
# Server port
PORT_NUMBER = 8080

# Form HTML
form = b"""<!DOCTYPE html>
<html>
    <head>
        <title>Hello User!</title>
    </head>
    <body>
        <form method="post">
            <label>Hello</label>
            <input type="text" name="name">
            <input type="submit" value="Go">
        </form>
    </body>
</html>\n"""


def application(environ, start_response):
    html_document = form

    if environ["REQUEST_METHOD"] == "POST":
        try:
            request_body_size = int(environ.get("CONTENT_LENGTH", 0))
        except (ValueError):
            request_body_size = 0
        # Read the request body
        request_body = environ["wsgi.input"].read(request_body_size)
        post = parse_qs(request_body.decode("utf-8"))
        name = post.get("name", ["World"])[0]
        html_document = b"Hello, " + bytes(name, "utf-8") + b"!"
    # Start the response
    start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
    return [html_document]


def run():
    """Run WSGI Server"""
    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()
    except KeyboardInterrupt:
        print(" <Ctrl-C> entered, stopping WSGI Server...")
        if server:
            server.socket.close()


if __name__ == "__main__":
    """Starting WSGI server"""
    run()
else:
    print(
        "This script should be run directly and not imported as a module.\n"
        "Please execute it using 'python wsgi_hello_world_post_request.py'."
    )

Aunque algo detallado, ha podido crear una aplicación web simple que maneja los datos POST suministrados.

Truco

Para ejecutar el código wsgi_hello_world_get_request.py y wsgi_hello_world_post_request.py, abra una consola de comando, acceda al directorio donde se encuentra ambos programas:

proyectos/
└── wsgi/
    └── wsgi_hello_world_post_request.py

Si tiene la estructura de archivo previa, entonces ejecute el siguiente comando:

python3 wsgi_hello_world_post_request.py

De esta forma puede una aplicación web WSGI simple que maneja una petición POST.


Importante

Usted puede descargar el código usado en esta sección haciendo clic en los siguientes enlaces:


Estos son los bloques de construcción muy simplificados utilizados en framework web populares como Flask y Django.

De esta forma ha aprendido a crear aplicaciones web WSGI que maneja peticiones GET y POST.


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