Introducción a Flask
¿Qué es Flask?
Creando tu primer "Hello, World" en Flask
Rutas y Plantillas con Jinja
Rutas y vistas en Flask
Plantillas con Jinja en Flask
Manejo de Formularios y Datos
Manejo de formularios en Flask
Bases de datos: SQLite y SQLAlchemy
CRUD: Crear y leer datos en Flask
CRUD: Actualizar datos en Flask
CRUD: Eliminar datos en Flask
Organización del Proyecto y Mejoras
Estructura de proyectos en Flask
Blueprints en Flask
Notificaciones con Flash Messages
Integración de TailwindCSS en Flask
Seguridad y Testing
Gestión de sesiones en Flask
Manejo de cierre de sesión en Flask
Validación de formularios en Flask
Pruebas unitarias en Flask
Próximos pasos en Flask
You don't have access to this class
Keep learning! Join and start boosting your career
The @route
decorator in Flask is a powerful tool that allows us to define how our web applications respond to different types of HTTP requests. Mastering this decorator is essential for creating robust APIs and interactive web applications that can process various types of user requests. In this article, we will explore how to extend our use of the @route
decorator to handle different HTTP methods and return various types of data.
@route
decorator with different HTTP methods?The @route
decorator in Flask not only allows us to define routes for GET requests, but we can also configure it to handle other HTTP methods such as POST, PUT or DELETE. This is essential for creating complete web applications that can receive and process different types of user interactions.
To specify which HTTP methods a particular route can handle, we use the methods
parameter:
@app.route('/contact', methods=['GET', 'POST'])def contact(): if request.method == 'POST': return "Form submitted successfully", 201 return "Contact page".
In this example, we have created a view that can respond to both GET and POST requests. It is important to note that if we do not specify the methods
parameter, Flask will assume by default that the route only handles GET requests.
To determine what type of HTTP method an incoming request is using, we can use Flask's request
object:
from flask import request
@app.route('/contact', methods=['GET', 'POST'])def contact(): if request.method == 'POST': # Logic for handling POST requests return "Form submitted successfully", 201 # Logic for handling GET requests return "Contact page" .
The request
object is imported directly from Flask and is automatically populated with the current request information. We do not need to pass it as a parameter to our view function.
Flask allows us not only to return content, but also to specify HTTP status codes and other metadata in our responses.
To return a specific status code along with our response, we simply include it as the second element in a tuple:
@app.route('/contact', methods=['GET', 'POST'])def contact(): if request.method == 'POST': # We return code 201 (Created) to indicate that something was successfully created return "Form submitted successfully", 201 return "Contact page" .
HTTP status codes are important to follow good web development practices:
Flask makes it easy to return different data formats, such as JSON, which is especially useful for web APIs:
from flask import jsonify
@app.route('/api/info')def api_info(): data = { " name": "notesApp", " version": "1.1.1" } return jsonify(data), 200
The jsonify()
function automatically converts Python dictionaries into JSON responses with the appropriate MIME headers. This is critical when we are developing APIs that need to communicate with frontend or mobile applications.
An interesting feature of Flask is that we can define URLs that are different from the name of the function that handles that route:
@app.route('/about')def about(): return "This is a notes app."
In this example, the function is called about
, but the URL that users will visit is /about-de
. This flexibility allows us to create friendly and semantically meaningful URLs while keeping clear function names in our code.
To test POST requests without having to create an HTML form, we can use tools such as curl
from the command line:
curl -X POST http://localhost:5000/contacto
This command will send a POST request to our path /contact
and show us the response, including the HTTP status code.
The use of tools like curl is invaluable during development to quickly test our endpoints without the need to create full user interfaces.
The @route
decorator in Flask is a versatile tool that allows us to create robust web applications and flexible APIs. Mastering its use with different HTTP methods and response types is essential for any web developer working with Python. I encourage you to experiment with HTML returns and explore other HTTP methods such as PUT and PATCH to expand your web development skills with Flask.
Contributions 4
Questions 0
{{ contenido }}
</body></html>` `@app.route('/pagina')def pagina(): return render_template('pagina.html', titulo='Barbería', contenido='Bienvenidos a nuestra barbería')`
Want to see more contributions, questions and answers from the community?