Sinvaldo [Profile]

Chief Operating Officer at Square Cloud

Article written by Sinvaldo in 28/01/2024.

Introduction to Flask

Flask is a lightweight web framework for Python that makes it easy to create fast and efficient web applications. In this guide, we will explore the basics of Flask and provide practical examples to help you get started.

Installation

With pip

To install Flask with pip, run the following command:

pip install flask

With Poetry

To start a Flask project with Poetry, first, make sure you have Poetry installed. If not, visit the official Poetry website for installation instructions.

Next, create a new directory for your project and navigate to it:

mkdir my_flask_project
cd my_flask_project

Now, start a new Poetry project and add Flask as a dependency:

poetry init -n
poetry add flask

This will create a pyproject.toml file and install Flask. Now, you can create the app.py file for your Flask application.

Creating a Basic Application

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run(debug=True)

Dynamic Routes

from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    return f'User profile: {username}'

if __name__ == '__main__':
    app.run(debug=True)

Jinja2 Templates

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', title='Home Page', content='Welcome to my site!')

if __name__ == '__main__':
    app.run(debug=True)

What is Flask For?

Flask is ideal for rapid web application development. It can be used to create everything from simple APIs to complex web applications. Its simplicity and flexibility make it a popular choice among Python developers.

Conclusion

This guide provides a practical introduction to Flask, from installation to creating dynamic routes and using Jinja2 templates. With this knowledge, you are ready to explore even more of Flask’s power in Python web development.