Última actualización: 15 de diciembre de 2023

4.3. Variables de entorno

El servidor rellena el diccionario de entorno con variables similares a CGI en cada solicitud del cliente. Es script generará todo el diccionario:

#!/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/environment-dictionary
"""

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

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)

    status = "200 OK"
    response_headers = [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(response_body))),
    ]
    start_response(status, response_headers)

    # return [response_body]
    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 print_environment.py, abra una consola de comando, acceda al directorio donde se encuentra el mismo, y ejecute el siguiente comando:

python print_environment.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.

Contrata mi increíble soporte profesional