Python 🪄

Python for Web Development: Flask Framework Fundamentals

Flask is a lightweight and flexible Python web framework that’s perfect for beginners and seasoned developers alike. In this tutorial, we’ll explore the fundamentals of Flask and build a simple web application from scratch. By the end, you’ll have a solid foundation in Flask web development.

Prerequisites

Before we begin, make sure you have:

Step 1: Setting Up Your Environment

First, let’s create a virtual environment and install Flask:

# Create a new directory for your project
mkdir flask_tutorial
cd flask_tutorial
# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
# Install Flask
pip install flask

Step 2: Creating Your First Flask Application

Let’s create a simple “Hello, World!” application. Create a new file called app.py:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello, World!'
if __name__ == '__main__':
    app.run(debug=True)

Run your application:

python app.py

Visit http://127.0.0.1:5000/ in your browser, and you should see “Hello, World!”.

Step 3: Understanding Routing

Flask uses decorators to define routes. Let’s add more routes to our application:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
    return 'Welcome to the Flask Tutorial!'
@app.route('/about')
def about():
    return 'This is the about page.'
@app.route('/user/<username>')
def show_user_profile(username):
    return f'User: {username}'
if __name__ == '__main__':
    app.run(debug=True)

Now you have three routes:

  • /: The home page
  • /about: An about page
  • /user/<username>: A dynamic route that accepts a username

Step 4: Working with Templates

Instead of returning plain text, let’s use HTML templates. First, create a templates folder in your project directory.

Create templates/base.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Flask Tutorial{% endblock %}</title>
</head>
<body>
    <nav>
        <a href="{{ url_for('home') }}">Home</a>
        <a href="{{ url_for('about') }}">About</a>
    </nav>
    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

Create templates/home.html:

{% extends "base.html" %}
{% block content %}
<h1>Welcome to the Flask Tutorial!</h1>
<p>This is the home page.</p>
{% endblock %}

Create templates/about.html:

{% extends "base.html" %}
{% block title %}About - {{ super() }}{% endblock %}
{% block content %}
<h1>About</h1>
<p>This is the about page of our Flask tutorial.</p>
{% endblock %}

Now, update app.py to use these templates:

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('home.html')
@app.route('/about')
def about():
    return render_template('about.html')
@app.route('/user/<username>')
def show_user_profile(username):
    return render_template('user.html', username=username)
if __name__ == '__main__':
    app.run(debug=True)

Create templates/user.html:

{% extends "base.html" %}
{% block title %}User: {{ username }} - {{ super() }}{% endblock %}
{% block content %}
<h1>User Profile</h1>
<p>Username: {{ username }}</p>
{% endblock %}

Step 5: Handling Forms

Let’s add a simple form to our application. Create templates/form.html:

{% extends "base.html" %}
{% block title %}Form - {{ super() }}{% endblock %}
{% block content %}
<h1>Sample Form</h1>
<form method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <button type="submit">Submit</button>
</form>
{% if name %}
<p>Hello, {{ name }}!</p>
{% endif %}
{% endblock %}

Update app.py to handle the form:

from flask import Flask, render_template, request
app = Flask(__name__)
# ... (previous routes) ...
@app.route('/form', methods=['GET', 'POST'])
def form():
    name = None
    if request.method == 'POST':
        name = request.form['name']
    return render_template('form.html', name=name)
if __name__ == '__main__':
    app.run(debug=True)

Step 6: Database Integration

For this example, we’ll use SQLite with SQLAlchemy. First, install the required packages:

pip install flask-sqlalchemy

Update app.py to include database functionality:

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    def __repr__(self):
        return f'<User {self.username}>'
# Create the database tables
with app.app_context():
    db.create_all()
@app.route('/')
def home():
    users = User.query.all()
    return render_template('home.html', users=users)
@app.route('/add_user', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        new_user = User(username=username, email=email)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('home'))
    return render_template('add_user.html')
# ... (other routes) ...
if __name__ == '__main__':
    app.run(debug=True)

Create templates/add_user.html:

{% extends "base.html" %}
{% block title %}Add User - {{ super() }}{% endblock %}
{% block content %}
<h1>Add User</h1>
<form method="POST">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <button type="submit">Add User</button>
</form>
{% endblock %}

Update templates/home.html to display users:

{% extends "base.html" %}
{% block content %}
<h1>Welcome to the Flask Tutorial!</h1>
<p>This is the home page.</p>
<h2>Users:</h2>
<ul>
    {% for user in users %}
    <li>{{ user.username }} ({{ user.email }})</li>
    {% endfor %}
</ul>
<a href="{{ url_for('add_user') }}">Add User</a>
{% endblock %}

Conclusion

Congratulations! You’ve now created a basic Flask web application with routing, templates, form handling, and database integration. This tutorial covered the fundamentals of Flask, but there’s much more to explore:

  • User authentication and authorization
  • RESTful API development
  • Flask extensions for additional functionality
  • Deployment to production servers

As you continue your journey with Flask, remember to consult the official Flask documentation for more detailed information and advanced topics. Happy coding, and may your web development adventures with Flask be ever exciting!

Dakidarts

Share
Published by
Dakidarts

Recent Posts

Inspiring Branded Content Examples: A Showcase

Looking for inspiration? Explore these captivating examples of branded content that effectively engage audiences and…

10 hours ago

OpenAI’s o1: A Self-Fact-Checking AI Model

OpenAI's latest AI model, o1, is a significant advancement in AI technology. Equipped with self-fact-checking…

10 hours ago

AI Chatbots: What is New?

AI chatbots have revolutionized communication and customer service. This comprehensive guide explores the technology behind…

11 hours ago

Google’s Monopoly: Will Anything Change?

Google's dominance in the search engine market has raised antitrust concerns. This article explores the…

11 hours ago

Shopsense AI: Shop the VMAs Looks with AI-Powered Dupes

Discover Shopsense AI, a platform that allows music fans to find and purchase fashion dupes…

19 hours ago

Rent Success: Expanding Your Reach Beyond Your Website

Explore the potential of publishing content beyond your website to reach a wider audience and…

19 hours ago