codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

59 / 68 topics
59Web Development with Flask60Django Framework Basics61Django ORM & Models62Django Templates & Jinja263Building REST APIs with Django Rest Framework (DRF)
Tutorials/Python Programming/Web Development with Flask
🐍Python Programming

Web Development with Flask

Updated 2026-04-20
3 min read

Web Development with Flask

Introduction

Flask is a micro web framework for Python based on Werkzeug and Jinja 2. It's lightweight, easy to use, and highly flexible, making it an excellent choice for building web applications of all sizes. This tutorial will guide you through the basics of setting up a Flask application, routing, templates, forms, and more.

Setting Up Your Environment

Before we start, ensure you have Python installed on your system. You can download it from python.org. Once Python is installed, you need to set up a virtual environment for your project:

# Create a new directory for your project and navigate into it
mkdir my_flask_app
cd my_flask_app

# Create a virtual environment
python -m venv venv

# Activate the virtual environment
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate

# Install Flask
pip install Flask

Creating Your First Flask Application

Let's create a simple "Hello, World!" application to get started:

# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

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

Explanation

  • Importing Flask: We import the Flask class from the flask module.
  • Creating an App Instance: app = Flask(__name__) creates an instance of the Flask class. The __name__ variable is passed to help Flask determine the root path of the application.
  • Defining a Route: The @app.route('/') decorator defines the route for the home page. When you visit the root URL, the hello_world function is called, and it returns the string "Hello, World!".
  • Running the App: if __name__ == '__main__': ensures that the app runs only if the script is executed directly (not imported). app.run(debug=True) starts the Flask development server with debug mode enabled, which provides detailed error messages and automatically reloads the server when code changes are detected.

Templates

Templates allow you to separate your Python code from HTML. Flask uses Jinja2 templating engine by default.

Creating a Template

  1. Create a folder named templates in the root of your project.
  2. Inside the templates folder, create a file named index.html.
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask App</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Rendering Templates

Modify your app.py to render the template:

# app.py
from flask import Flask, render_template

app = Flask(__name__)

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

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

Explanation

  • render_template: This function renders a template. It takes the name of the template file and any variables you want to pass to the template.

Forms

Flask provides tools for handling forms, including form validation and CSRF protection.

Creating a Form

  1. Install Flask-WTF, an extension that integrates WTForms with Flask:
pip install Flask-WTF
  1. Create a form class in forms.py:
# forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    submit = SubmitField('Submit')
  1. Update app.py to handle the form:
# app.py
from flask import Flask, render_template, request
from forms import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

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

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

Explanation

  • Flask-WTF: This extension provides CSRF protection and integrates WTForms with Flask.
  • Form Class: MyForm is a subclass of FlaskForm. It defines fields using WTForms classes and validators.
  • Handling Form Submission: In the route, we create an instance of the form. If the form is submitted and valid, we process the data (in this case, just displaying it).

Updating Template

Update index.html to include the form:

<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask App</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.name.label }} {{ form.name(size=20) }}
        {{ form.submit() }}
    </form>
</body>
</html>

Explanation

  • Form Fields: We render the form fields using Jinja2 syntax. {{ form.hidden_tag() }} is required for CSRF protection.

Static Files

Static files like CSS, JavaScript, and images are stored in a folder named static.

  1. Create a folder named static in the root of your project.
  2. Add a CSS file, e.g., style.css, inside the static folder:
/* static/style.css */
body {
    font-family: Arial, sans-serif;
}
  1. Update index.html to link the CSS file:
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask App</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.name.label }} {{ form.name(size=20) }}
        {{ form.submit() }}
    </form>
</body>
</html>

Explanation

  • url_for: This function generates URLs for static files. filename='style.css' specifies the path to the CSS file.

Conclusion

Flask is a powerful and flexible framework for building web applications in Python. In this tutorial, we covered setting up a basic Flask application, using templates, handling forms, and managing static files. These concepts form the foundation of more complex Flask applications. As you continue learning, explore Flask extensions like Flask-SQLAlchemy for database integration, Flask-Login for user authentication, and Flask-Migrate for database migrations.

Remember to always keep your virtual environment activated when working on your Flask projects, and use pip freeze > requirements.txt to save your dependencies for easy setup in other environments. Happy coding!


PreviousTensorFlow & PyTorch BasicsNext Django Framework Basics

Recommended Gear

TensorFlow & PyTorch BasicsDjango Framework Basics