Flask 프로젝트 구조 (templates / static 분리)
Flask는 파일 하나로도 서버를 만들 수 있지만, 실제로는 기능이 늘어나면서 파일을 분리하는 구조가 필요하다.
프로젝트 구조를 잘 잡아두면 라우팅, 템플릿, 정적 파일(CSS/JS/이미지), 설정을 관리하기가 훨씬 편해진다.
Flask에서 기본적으로 자주 쓰는 폴더는 다음과 같다.
Flask는 기본 설정으로 templates와 static 폴더를 자동으로 인식한다.
그래서 별도 설정 없이도 파일을 넣기만 하면 사용할 수 있다.
기본 구조 예시 (가장 단순)
myflask/
├── app.py
├── templates/
│ └── index.html
└── static/
├── css/
│ └── style.css
└── js/
└── main.js
이 구조는 템플릿과 정적 파일을 분리해서 관리하는 가장 기본 형태다.
템플릿 연결
Flask에서 HTML을 반환할 때는 render_template()를 사용한다.
from flask import render_template
@app.route("/")
def home():
return render_template("index.html")
정적 파일 연결
정적 파일은 HTML에서 url_for("static", filename="...") 형태로 연결한다.
CSS 연결 예시
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
JS 연결 예시
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
이미지 연결 예시
<img src="{{ url_for('static', filename='img/logo.png') }}">
파일이 많아졌을 때 구조 확장
프로젝트가 커지면 보통 다음처럼 분리한다.
myflask/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── templates/
│ └── static/
├── run.py
└── requirements.txt
app/ 안에 실제 Flask 코드들을 모아두고 run.py에서 실행하는 형태로 많이 사용한다
폴더 구조
myflask/
├── app.py
├── templates/
│ └── index.html
└── static/
└── css/
└── style.css
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Flask 구조</title>
</head>
<body>
<h1>Flask Templates + Static</h1>
</body>
</html>
static/css/style.css
h1 {
font-size: 40px;
}