0Pricing
Flask Academy · Lección

Ramifique la lógica según request.method

Muestre un formulario con GET y procéselo con POST.

Ramifique la lógica según request.method es una lección gratuita de Flask Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Flask Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Flask Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

One Route, Two Jobs

A route that accepts both GET and POST often needs to behave differently for each. You handle that by checking which verb arrived.

The request Object

Flask gives you a global request object that describes the incoming call. Import it once and use it inside any view.

from flask import request

Read request.method

The attribute request.method holds the verb of the current call as a string like "GET" or "POST".

if request.method == "POST":
    print("handling a form")

Branch on the Verb

Wrap your logic in an if that checks request.method. One branch shows a form, the other processes the submitted data.

The Classic Form Pattern

The most common shape is: on GET render the empty form, and on POST read the answers and act on them.

@app.route("/contact", methods=["GET", "POST"])
def contact():
    if request.method == "POST":
        return "saved"
    return "show form"

GET Should Not Change Data

Keep the GET branch read-only. A GET request must never create or modify records, since browsers may repeat it freely.

POST Does the Work

Put writes, saves, and side effects in the POST branch. That keeps mutations tied to a deliberate submission.

Compare Strings Exactly

Always compare against the exact uppercase value. request.method is "POST", never "post", so a lowercase check will silently fail.

An else for the Fallthrough

Treat the GET case as the natural else. Return the form view when the method is not POST so the page always renders.

Skip Checks Flask Handles

You never test for a verb you did not allow. Flask blocks unlisted methods before your code runs, so only listed verbs arrive.

Keep Branches Small

If each branch grows large, call helper functions from the if. The view stays a clean dispatcher between GET and POST.

Quick Check

Pick the branch that should change data.

Recap

Use request.method to branch: render the form on GET, process and save on POST. Keep GET read-only and POST for changes. Great work! 🙌

Preguntas frecuentes

¿La lección «Ramifique la lógica según request.method» es gratis?

Sí — el texto completo de «Ramifique la lógica según request.method» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Flask Academy, actualiza a CoddyKit PRO. El curso de Flask Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Ramifique la lógica según request.method»?

Muestre un formulario con GET y procéselo con POST. Practicas Flask Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Flask Academy?

No se requiere experiencia previa. Flask Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Ramifique la lógica según request.method»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Flask Academy?

Sí. Cada lección de Flask Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Declare los métodos permitidos en una ruta
  2. Ramifique la lógica según request.method
  3. Lea datos POST del cuerpo
  4. Explicación de 405 Method Not Allowed
← Volver a Flask Academy