Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
13 Hrs
52 Min
11 Seg
Curso de Flask

Curso de Flask

Luis Mart铆nez

Luis Mart铆nez

Creando tu primer "Hello, World" en Flask

2/18
Resources
Transcript

Creating web applications with Flask is a fundamental skill for Python developers looking to build lightweight and efficient web solutions. This micro-framework offers the flexibility needed to develop from simple APIs to complex web applications, while maintaining a minimalist approach that makes it easy to learn. Next, we will explore how to set up a Flask development environment and create our first note application.

How to set up a development environment for Flask?

Before you start programming with Flask, it is essential to set up a suitable development environment. The use of virtual environments is a recommended practice that allows us to isolate the dependencies of each project and avoid conflicts between package versions.

To create our working environment, we will follow these steps:

  1. Create a folder for our project:

    mkdir notes-appcd notes-app
  2. Generate a virtual environment inside this folder:

    python -m venv venv
  3. Activate the virtual environment:

    • On Unix/Linux/MacOS systems:
      source venv/bin/activate
    • On Windows systems (the specific command will be available in the additional resources)
  4. Install Flask using pip:

    pip install Flask
  5. Verify the installation:

    flask --help

Once these steps are completed, we will have an isolated environment with Flask installed and ready to use. This configuration allows us to keep the dependencies organized and facilitates the portability of the project between different systems.

How to open the project in Visual Studio Code?

To work comfortably with our code, we can open the project folder in Visual Studio Code directly from the terminal:

code -r .

This command will open VS Code with the current folder as the root of the project, allowing us to easily create and edit files.

How to create our first Flask application?

Once our environment is configured, we can start writing the code for our application. Flask is based on a system of paths and views that allows us to define what content will be displayed in each URL of our application.

We will create a file called app.py with the following content:

from Flask import Flask
app = Flask(__name__)
 @app.route('/')def hello(): return "Hello World"
if __name__ == '__main__': app.run(debug=True)

This code performs several important actions:

  1. Imports the Flask class from the main package.
  2. Creates an instance of the application
  3. Defines a path to the root URL ('/')
  4. Attaches a function that returns the text "Hello World".
  5. Configures the application to run in debug mode when the file is run directly

How to run our Flask application?

There are two main ways to run a Flask application:

  1. Using Python directly:

    python app.py
  2. Using the Flask command (recommended):

    flask run

The second option is preferable because:

  • It eliminates the need to include the if __name__ == '__main__' block in our code.
  • It provides additional options through flags
  • It is the standard way recommended by Flask.

To enable debug mode with the Flask command, we use:

flask run --debug

The debug mode is extremely useful during development because:

  • Automatically reloads the application when it detects code changes.
  • Provides detailed error messages
  • Includes an interactive console for debugging

However, it is important to remember that it should never be used in production for security and performance reasons.

What additional options does the Flask command offer?

Flask provides several options to customize the execution of our application. We can explore them by running

flask run --help

Among the available options we find:

  • Change the host and listening port
  • Enable or disable the debugging mode
  • Specify additional files to monitor changes
  • Configure threading options

How to create additional routes in our application?

A web application typically needs multiple pages or endpoints. In Flask, we can create as many routes as we need using the @app.route() decorator.

For example, to add an "About" page to our notes application, we could add:

@app.route('/about')def about(): return "This is an application for taking and organizing personal notes.  You will be able to easily create, edit and delete notes."

Each route is associated with a specific function that determines what content will be displayed when a user visits that URL. These functions can return plain text, HTML, JSON or other types of content depending on the needs of the application.

The path structure is critical to organizing the navigation of our application and providing a consistent user experience.

Flask is a powerful and flexible micro-framework that allows us to create web applications quickly and easily. We have learned how to set up a development environment, create a basic application and add paths for different pages. These fundamental concepts are the basis for building more complex applications in the future. What other features would you like to implement in your notes application? Share your ideas in the comments.

Contributions 5

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

![](https://static.platzi.com/media/user_upload/image-9346a276-ac63-4f84-a0e7-e92aae0ba5c0.jpg)
**Holaa!** Puede que me est茅 adelantando un poco al curso, pero quer铆a compartir un peque帽o fragmento de c贸digo que permite crear una ruta din谩mica en Flask, pasando un par谩metro en la URL. Con este c贸digo: `@app.route('/notes/<number>/'`) `def notes(number`): ` return (f'This is the notes page that can help you with notes.'` ` f'\nParameter: {number}`' ` f'\nLook the URL'`) Se puede acceder a la ruta `/notes/1/`, `/notes/hello/`, etc., y ver c贸mo el par谩metro se refleja en la respuesta. 隆Espero que a alguien le sirva! 馃槉
```python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hola mundo!" @app.route("/notes") def take_notes(): return "Welcome, write your notes!" if __name__ == "__main__": app.run(debug=True) ```from flask import Flask app = Flask(\_\_name\_\_) @app.route("/")def hello():聽 聽 return "Hola mundo!" @app.route("/notes")def take\_notes():聽 聽 return "Welcome, write your notes!"if \_\_name\_\_ == "\_\_main\_\_":聽 聽 app.run(debug=True)
Envio aqui el desafio de esta clase. ```python from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hola Mundo" @app.route("/about") def about(): return "Esta es una aplicaci贸n para tomar notas." if __name__ == "__main__": app.run(debug=True ```
Creo que va muy r谩pido el curso. Adem谩s no est谩 adaptado a usuarios con sistema operativo windows, parece que el instructor tiene Mac. Creo que deber铆a cuidar esos peque帽os detalles finos e indicarlo al inicio...