DEV Community

Cover image for Ignite with Flask
Patrick Dacius
Patrick Dacius

Posted on

Ignite with Flask

Introduction

Are you new to Python? If so, you're looking for some libraries and frameworks that can help you kickstart creating your first of many projects. ****Python is a powerful language that can help you build anything, from automation tools to web apps. In this post, we’ll dive into Flask step-by-step and guide you through installing this framework and setting up your framework to get started for building your very first project. Let’s get started!

What is Flask?

Flask is a framework that is written in Python that helps in the aid of the development of an application by providing crucial and necessary back-end components. Not only is Flask a framework but it is also considered a “micro” lightweight framework, this is due to the focus on providing the core functionalities essential for web development without implementing unnecessary components, allowing the ability to enhance customization and performance. When a developer's priority is simplicity, control Flask is the way to go.

Why use the Flask framework?

Now that you know a little bit about what Flask is, let's talk about some of the reasons why a beginner like me and yourself should use this framework and its key features.

1. Lightweight and Minimalistic:

Flask is a micro web framework, as said previously. We are only provided with the tools to get the application we are creating running without having to implement strict/unnecessary additions. This is best used for medium-to-small-sized apps and projects.

2. Easy to Learn for Beginners:

Flask has a design that is straightforward. This allows beginners to grasp the fundamentals of Flask and web development more easily. Flask has excellent official documentation with beginner-friendly examples and guides.

3. Flexibility and Customization:

Flask is unlike other frameworks. With this framework, you are allowed to use the libraries and extensions of your choice. You have the freedom to decide how to structure your code, handle the database, and manage any user authorization and authentication, etc.

  • Some of the libraries or Flask-specific extensions that are frequently used are:
    • Flask-SQLAchemy for database integration
    • Flask-WTF for form validation
    • Flask-login for user authentication

4. Built-In Development Server and Debugger

Another cool reason to use the Flask framework is due fo the built-in development sever and debugging, which makes the testing and troubleshooting easier during the development of the web application. The debugger allows for the creator to inspect the returned errors directly within the browser.

5. Ideal for Prototypes

Because Flask is a lightweight framework, it is perfect for building prototypes and MVPs. It lets you quickly test the ideas that you have without the effects of a heavy framework

Getting Started With Flask

Prerequisites:

Before starting Flask we need to make sure of a few things:

  1. Python Installed: Flask is a Python framework, so the use of Flask cannot be done without having Python.

    Check if Python is installed by running:

    python --version
    

(If you don't have Python installed, a simple google search to Python.org will help you get that problem fixed)

  1. Pip (Python Package Installer): Pip usually comes pre-installed with Python but you should always check and verify it by running:

    pip --version
    
  2. A Code Editor: Use a Code editor of your choice to write your Flask code. My code editor of choice is VSCode.

  3. Terminal or Command Line: This is to run your Flask application.

Step-by-step Guide to Set Up Flask

  1. Set Up a Project Directory:

Create a new directory for your Flask project and navigate to the project using your terminal:

mkdir flask_blog_project
cd flask_blog_project
Enter fullscreen mode Exit fullscreen mode
  1. Create a Virtual Environment:

A virtual environment helps isolate project dependencies. Run the following code:

python -m venv venv 
Enter fullscreen mode Exit fullscreen mode

This creates a virtual environment called venv.

  • Activate the Virtual Environment:

    • On macOS/Linux:

      source venv/bin/activate
      
    • On Windows:

    venv\Scripts\activate
    

Your terminal should show (venv) at the start, which indicates the environment is active.

  1. Install Flask:

Install Flask using pip within the activated virtual environment:

pip install flask
Enter fullscreen mode Exit fullscreen mode

Verify the installation:


python -C 'import flask; print(flask.__version__)'
Enter fullscreen mode Exit fullscreen mode
  1. Create a basic Flask Application

    In your project folder, create a new file called app.py with the following code:

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return "Hello, Blog reader! Welcome to my flask set up."
    
    if __name__ == '__main__':
        app.run(debug=True)
    
  2. Run the Flask Application

    Set up FLASK_APP environment variable:

- On macOS/Linux:
Enter fullscreen mode Exit fullscreen mode
    ```
    export FLASK_APP=app
    ```
Enter fullscreen mode Exit fullscreen mode
- On Windows (Command Prompt):
Enter fullscreen mode Exit fullscreen mode
    ```
    set Flask_APP=app
    ```
Enter fullscreen mode Exit fullscreen mode
1. Start the Flask development server:
Enter fullscreen mode Exit fullscreen mode
    ```bash
    flask run
    ```
Enter fullscreen mode Exit fullscreen mode
2. Open your browser and go to http://127.0.0.1:5000/. You should see:
Enter fullscreen mode Exit fullscreen mode
    ```css
    Hello, Blog reader! Welcome to my flask set up.
    ```
Enter fullscreen mode Exit fullscreen mode
  1. Add More Routes:

    To make your app dynamic, add more routes. Update your app.py :

    @app.route('/about')
    def about():
        return "You are on the About Page."
    
    @app.route('/greet/<name>')
    def greet(name):
        return f"Hello, {name.capitalize()}!"
    
    
- **Restart the Flask server** (Ctrl+C to stop and `flask run` to restart).
- Visit these routes in the browser:
    - http://127.0.0.1:5000/about
    - http://127.0.0.1:5000/greet/yourname
Enter fullscreen mode Exit fullscreen mode
  1. Learn About Templates and Static Files

    Flask supports dynamic HTML rendering using the Jinja2 templating engine. For example:

- Create a folder called `templates` in your project directory.
- Inside `templates`, create an `index.html` file:
Enter fullscreen mode Exit fullscreen mode
```html
<!DOCTYPE html>
<html>
<head><title>Flask App</title></head>
<body>
    <h1>Welcome to my application, {{ name }}!</h1>
</body>
</html>
```
Enter fullscreen mode Exit fullscreen mode
- Update `app.py` to render the template:
Enter fullscreen mode Exit fullscreen mode
```python
from flask import render_template

@app.route('/welcome/<name>')
def welcome(name):
    return render_template('index.html', name=name)
```
Enter fullscreen mode Exit fullscreen mode
  • Restart the Flask server and visit:

    http://127.0.0.1:5000/welcome/yourname
    
  1. Explore Flask Extensions:

Flask has many extensions to help you add features. Some common ones include:

  • Flask-SQLAlchemy: For database integration.
  • Flask-Login: For user authentication.
  • Flask-WTF: For form handling.

Install an extension using pip, for example:

pip install flask-sqlalchemy
Enter fullscreen mode Exit fullscreen mode

Top comments (0)