🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Project Layout

A project layout is the file plan of an app. Small apps keep a few files, each with one job.

Build the layout

This code makes the two folders and writes the four files of a small project.

import os

os.makedirs("templates", exist_ok=True)
os.makedirs("static", exist_ok=True)
with open("app.py", "w") as f:
    f.write("from flask import Flask\n")
with open("requirements.txt", "w") as f:
    f.write("flask\n")
with open("templates/home.html", "w") as f:
    f.write("<h1>Hi</h1>")
with open("static/style.css", "w") as f:
    f.write("h1 { color: blue; }")

Check the files exist

This loop checks each file in turn and prints its name with True when the file is there.

for path in ["app.py", "requirements.txt", "static/style.css", "templates/home.html"]:
    print(path, os.path.exists(path))

Example

import os

os.makedirs("templates", exist_ok=True)
os.makedirs("static", exist_ok=True)
with open("app.py", "w") as f:
    f.write("from flask import Flask\n")
with open("requirements.txt", "w") as f:
    f.write("flask\n")
with open("templates/home.html", "w") as f:
    f.write("<h1>Hi</h1>")
with open("static/style.css", "w") as f:
    f.write("h1 { color: blue; }")

for path in ["app.py", "requirements.txt", "static/style.css", "templates/home.html"]:
    print(path, os.path.exists(path))

Key points

  • app.py holds the app and its routes.
  • templates/ holds the template files.
  • static/ holds CSS and images.
  • requirements.txt lists the packages to install.

In this example, the program makes the templates and static folders and writes the four files of a small project. The loop then checks each file in turn. The prints show each name with True, so every file is there.

Note

One folder per job keeps a project easy to find.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which file holds the app and its routes in the small project layout?