Flask / Flask Basics

Basic Flask Application Structure

This tutorial focuses on the basic structure of a Flask application. You'll learn about the typical organization of a Flask project and how to structure your own projects effectiv…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Introduces Flask, its features, and basic concepts including routing, templates, and request handling.

1. Introduction

This tutorial aims to guide you in understanding the basic structure of a Flask application. Flask is a popular lightweight web framework in Python that comes in handy when developing web applications. By the end of this tutorial, you will learn how to structure your Flask application effectively, and this knowledge will aid in maintaining and scaling your projects with ease.

Prerequisites: Basic knowledge of Python and web development concepts.

2. Step-by-Step Guide

A Flask application typically consists of the following files and directories:

  • app.py: This is the main entry point of your application where you'll define routes and views.
  • templates/: This directory contains all your Jinja2 templates which are used to generate HTML from your views and models.
  • static/: This is where all your static files like CSS, JavaScript, images go.
  • models.py: (optional) If you're using a database, models are defined here.
  • forms.py: (optional) If you're using Flask-WTF or similar library for forms, you define your forms here.

Best practices and tips:

  • Always separate your application into logical components. For instance, separate models, forms, and routes into different modules.
  • Use the templates/ and static/ directories for HTML and static files respectively.
  • Always manage your dependencies with a requirements.txt file.

3. Code Examples

Consider the following example of a basic Flask application:

# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

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

In the above code snippet:

  • We first import the Flask module and create a Flask web server from the Flask module.
  • @app.route('/') is a decorator in Flask, which tells the application to call the associated function when the specified URL is visited.
  • def home(): defines a function that returns "home.html" file to the user's browser when a request comes from the browser.
  • if __name__ == '__main__': ensures the server only runs if the script is executed directly from the Python interpreter and not used as an imported module.

Expected output: When you navigate to http://localhost:5000/, you should see the contents of "home.html".

4. Summary

In this tutorial, we covered the basic structure of a Flask application. You've learned about the main components of a Flask application and their purpose. You now know how to structure your Flask application effectively.

For further learning, you can explore Flask documentation, tutorials, and other resources available online.

5. Practice Exercises

  1. Create a new route /about and a new function about() that returns an 'about.html' page.
  2. Create a route /user/<username> that takes username as input and returns a 'Hello, username' message.
  3. Add a static CSS file to your application and use it to style your home page.

Solutions

  1. To create a new route and function:
@app.route('/about')
def about():
    return render_template('about.html')
  1. To create a route with variable parts:
@app.route('/user/<username>')
def profile(username):
    return 'Hello, %s!' % username
  1. Add a file style.css in static/ directory. You can use it in your HTML as follows:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

Remember to keep practicing and building projects with Flask to get the hang of it!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help