4.5. Request GET¶
La petición GET en WSGI es una forma de enviar datos al servidor
a través de la URL.
Ejecute el script print_environment.py nuevamente y esta vez llámalo así:
http://localhost:8051/?age=10&hobbies=software&hobbies=tunning
Compruebe las variables QUERY_STRING y las REQUEST_METHOD en el diccionario environ:
QUERY_STRING: age=10&hobbies=software&hobbies=tunning
REQUEST_METHOD: GET
Cuando el método de solicitud es GET las variables del formulario se enviarán en la URL en
la parte llamada cadena de consulta, es decir, todo lo que se encuentra después del carácter
? en la URL.
Observe que la variable hobbies aparece dos veces. Puede ocurrir cuando hay casillas de
verificación en el formulario o cuando el usuario escribe la misma variable más de una vez
en la URL.
Es posible escribir código para analizar la cadena de consulta y recuperar esos valores, pero
es más fácil usar la función parse_qs() que devuelve un diccionario con los valores
como listas.
Siempre tenga cuidado con la entrada de datos del usuario. Debe desinfectar los valores enviados
por el formulario para evitar la inyección de secuencias de comandos maliciosos. La función
escape() se puede utilizar para eso.
La etiqueta HTML form en este script indica al navegador que realice una solicitud GET
(method="get"):
"""Python's bundled WSGI server
Source code taken and improvements from the
"WSGI Tutorial" by Clodoaldo Pinto Neto at
https://wsgi.tutorial.codepoint.net/parsing-the-request-get
"""
import logging
from urllib.parse import parse_qs
from html import escape
logging.basicConfig(level=logging.INFO)
# Server IP
HOST_NAME = "localhost"
# Server port
PORT_NUMBER = 8080
# HTTP Status
STATUS = "200 OK"
html = """<!DOCTYPE html>
<html>
<body>
<form method="get" action="">
<p>
Age: <input type="text" name="age" value="%(age)s">
</p>
<p>
Hobbies:
<input
name="hobbies" type="checkbox" value="software"
%(checked-software)s
> Software
<input
name="hobbies" type="checkbox" value="tunning"
%(checked-tunning)s
> Auto Tunning
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<p>
Age: %(age)s<br>
Hobbies: %(hobbies)s
</p>
</body>
</html>\n"""
def application(environ, start_response):
# Returns a dictionary in which the values are lists
environ_vars = parse_qs(environ["QUERY_STRING"])
# As there can be more than one value for a variable then
# a list is provided as a default value.
age = environ_vars.get("age", [""])[0] # Returns the first age value.
hobbies = environ_vars.get("hobbies", []) # Returns a list of hobbies.
# Always escape user input to avoid script injection
age = escape(age)
hobbies = [escape(hobby) for hobby in hobbies]
response_body = html % { # Fill the above html template in
"checked-software": ("", "checked")["software" in hobbies],
"checked-tunning": ("", "checked")["tunning" in hobbies],
"age": age or "Empty",
"hobbies": ", ".join(hobbies or ["No Hobbies?"]),
}
# Now content type is text/html
RESPONSE_HEADERS = [
("Content-Type", "text/html"),
("Content-Length", str(len(response_body))),
]
# Start the response
start_response(STATUS, RESPONSE_HEADERS)
return [response_body.encode("utf-8")]
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
)
logging.info(
f"WSGI Server running on http://{HOST_NAME}:{PORT_NUMBER}/ use <Ctrl-C> to stop."
)
# Server serve forever
server.serve_forever()
except KeyboardInterrupt:
logging.error("<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_get_request.py, abra una consola de
comando, acceda al directorio donde se encuentra el mismo, y ejecute el siguiente
comando:
python3 wsgi_get_request.py
De esta forma, una vez ejecutado el comando, el servidor estará atendiendo peticiones, puede abrir desde con su navegador Web favorito (Mozilla Firefox, Google Chrome, etc) la siguiente dirección http://localhost:8080
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.