Flask is a lightweight, easy-to-use web framework written in Python. It allows developers to quickly create web applications without the complexity of heavier frameworks like Django. Flask is often described as a “micro-framework,” meaning that it provides the essential tools to get a web app running but leaves much of the configuration and decision-making up to the developer.

In this tutorial, we’ll walk you through building a simple web application with Flask. By the end of this guide, you’ll have a basic understanding of Flask’s key features and how to develop your own simple web apps.


Table of Contents

  1. What is Flask?
  2. Setting Up Your Environment
  3. Creating Your First Flask Application
  4. Understanding Routes and Views
  5. Templates in Flask
  6. Handling Forms and User Input
  7. Running and Testing Your Application
  8. Best Practices
  9. Conclusion

What is Flask?

Flask is a micro-framework for building web applications. It’s called “micro” because it doesn’t come with a lot of pre-built tools like database management or form handling, which are common in other frameworks like Django. However, Flask is highly extensible, and you can add libraries or modules as needed.

Flask works based on the WSGI (Web Server Gateway Interface) standard and uses Jinja2 for templating and Werkzeug for routing and request handling.

The core components of a Flask application are:

  • Routes: URLs that users can visit to view pages or interact with the app.
  • Views: Functions that handle requests and return responses (usually in the form of HTML).
  • Templates: HTML files that are rendered dynamically with Python code using the Jinja2 template engine.

Setting Up Your Environment

Before we start coding, you’ll need to set up a Python environment to work with Flask.

1. Install Python

Make sure Python is installed on your machine. You can download it from here.

2. Install Flask

The next step is to install Flask. It’s best to use a virtual environment to keep your project dependencies isolated.

  • Open your terminal (or Command Prompt on Windows).
  • Create a new directory for your project and navigate into it:
  mkdir flask_tutorial
  cd flask_tutorial
  • Create a virtual environment:
  python -m venv venv
  • Activate the virtual environment:
  • Windows:
    bash venv\Scripts\activate
  • Mac/Linux: source venv/bin/activate
  • Install Flask using pip:
  pip install Flask

Once Flask is installed, you can start coding your Flask application.


Creating Your First Flask Application

Let’s create a simple “Hello, World!” application to get started.

Step 1: Create a New Python File

Inside your project directory, create a new Python file called app.py:

touch app.py

Step 2: Write the Flask Application Code

Open app.py in a text editor and write the following code:

from flask import Flask

# Create an instance of the Flask class
app = Flask(__name__)

# Define a route for the root URL
@app.route('/')
def hello_world():
    return 'Hello, World!'

# Run the application
if __name__ == '__main__':
    app.run(debug=True)

Step 3: Run the Application

To run the app, execute the following command in the terminal:

python app.py

You should see output similar to:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now, open your web browser and go to http://127.0.0.1:5000. You should see “Hello, World!” displayed on the page.


Understanding Routes and Views

In Flask, routes are URLs that a user can visit, and views are functions that respond to those requests.

  • Route: A URL pattern that Flask uses to match requests.
  • View: A Python function that executes when a route is requested.

In the code above, @app.route('/') creates a route for the homepage (the root URL). When someone visits this URL, Flask calls the hello_world() function, which returns a string that is sent back to the user’s browser.


Templates in Flask

Flask supports dynamic HTML generation through Jinja2 templates. This allows you to inject data from Python into HTML files, making the page content dynamic.

Step 1: Create a Template

Create a new directory called templates in your project folder. Inside this folder, create a new file called index.html:

mkdir templates
touch templates/index.html

Step 2: Modify the index.html Template

Inside index.html, write the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Tutorial</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
</html>

Step 3: Modify the Flask App to Use the Template

Update your app.py to render the index.html template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html', message='Hello, World!')

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

Now when you visit http://127.0.0.1:5000, you’ll see the message rendered in the HTML template.


Handling Forms and User Input

A common feature in web applications is the ability to accept user input via forms. Let’s add a simple form to your app.

Step 1: Update the Template to Include a Form

Modify the index.html file to include a form:

<form method="POST">
    <input type="text" name="username" placeholder="Enter your name">
    <button type="submit">Submit</button>
</form>

Step 2: Handle Form Data in Flask

Modify your app.py to handle the POST request and capture the form input:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    if request.method == 'POST':
        username = request.form['username']
        return f'Hello, {username}!'
    return render_template('index.html')

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

Now, when a user submits the form, Flask captures the username input and displays it on the page.


Running and Testing Your Application

To run and test your application, follow these steps:

  1. Run python app.py from the terminal.
  2. Open a web browser and go to http://127.0.0.1:5000.
  3. Try entering a name in the form and submitting it to see the result.

Best Practices

  1. Structure Your Project: As your app grows, organize your project into multiple files (e.g., separate files for routes, models, and templates). For larger projects, consider using Blueprints to structure your app into modular components.
  2. Use Environment Variables: Don’t hardcode sensitive data (like passwords or API keys) directly in your code. Use environment variables or Flask’s configuration system to manage such data.
  3. Testing: Flask makes it easy to write tests for your app. Use the unittest or pytest libraries to write tests that ensure your app behaves as expected.
  4. Security: Always sanitize user input to avoid security vulnerabilities like SQL injection or cross-site scripting (XSS). Flask provides tools like wtforms to handle form validation securely.

Conclusion

Congratulations! You’ve just built a simple Flask web application. We’ve covered the basics: setting up Flask, routing, rendering templates, and handling forms. You’re now ready to explore more advanced features like databases, authentication, and deploying your app.

To keep learning, consider reading Flask’s official documentation, exploring third-party libraries like Flask-SQLAlchemy for database integration, and experimenting with more complex web applications.

Good luck, and happy coding!

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *