Flask Front構成
📏 ディレクトリ構成
.
├── app
│ ├── __init__.py
│ ├── models/
│ │ └── __init__.py
│ ├── routes/
│ │ └── __init__.py
│ ├── services
│ │ └── __init__.py
│ ├── static
│ │ └── css/
│ │ └── base.css
│ └── templates
│ └── base.html
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
└── run.py
📝 requirements.txt
Flask
🐳 Dockerfile
- python:3.10-slimイメージをベースにコンテナ作成
- コンテナの作業場所をappに指定
- pythonモジュールpipインストール用のテキストをコンテナにコピー
- pythonモジュールをpipコマンドでインストール
- ローカルのファイルをコンテナにコピー
- flask appを起動
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "run.py"]
🐳 docker-compose.yml
- version
3
- サービスは
web
で構成
- dockerイメージは
flask
- dockerコンテナ名は
front_end
- ビルドは 現在のディレクトリ
.
配下の Dockerfile
を使用
- ポート番号フロント(ローカル)
80
番からコンテナの5000
番にアクセス
- 常時、再起動設定を設定
- 変更を即反映させるためローカル環境の現在のディレクトリ
.
とコンテナの /app
ディレクトリを接続
version: '3'
services:
web:
image: flask
container_name: front_end
build:
context: .
dockerfile: Dockerfile
ports:
- 80:5000
restart: always
volumes:
- .:/app
🎨 app/static/css/base.css
- アプリ全体共通ルールを設定
- 色、フォントサイズ
- その他は個別のファイルで設定し上書きをする
:root {
--base-color: #f5f5f5;
--main-color: #f17979;
--accent-color: #afd1bb;
--small-fontsize: 12px;
--medium-fontsize: 18px;
--large-fontsize: 24px;
}
body {
background-color: var(--base-color);
font-size: var(--medium-fontsize);
}
🏠 app/templates/base.html
- ベースのHTMLファイルBootstrapを設定しておく
<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>[{% block title %}Template Site{% endblock %}]</title>
<!-- Bootstrap CSSを読み込み -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/base.css') }}"
/>
{% block head %}{% endblock %}
</head>
<body>
{% block content %} {% endblock %}
<!-- Bootstrap JSを読み込み -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
🏠 app/templates/index.html
<!-- templates/index.html -->
{% extends "base.html" %}
{% block title %}{{ page_settings["title"] }}{% endblock %}
{% block content %}
{% endblock %}
🌐 app/routes/index.py
from flask import Blueprint, render_template
index_bp = Blueprint("index", __name__)
PAGE_SETTINGS = {
"title": "ホーム"
}
@index_bp.route("/")
def index_page():
return render_template("index.html", page_settings=PAGE_SETTINGS)
🌐 app/routes/init.py
app/routes
配下に作った****_bp
を登録していく
from app.routes.index import index_bp
def register_bp(app):
app.register_blueprint(index_bp)
🔴 app/init.py
- アプリケーションのイニシャル処理
- app生成
- エンドポイントBlueprintを登録
from flask import Flask
from app.routes import register_bp
def create_app():
app = Flask(__name__)
register_bp(app)
return app
🏃 run.py
from app import create_app
if __name__ == "__main__":
app = create_app()
app.run(host="0.0.0.0", debug=True)