はじめに
今回は、PythonとHTMLを使ってシンプルなカレンダーアプリを作成する方法をご紹介します。PythonのFlaskフレームワークを使用して、動的にHTMLページにカレンダーを表示します。初めてFlaskを使う方にもわかりやすいように、ステップバイステップで解説していきます。
必要なツール
- Python 3.x
- Flask(PythonのWebフレームワーク)
- 任意のコードエディタ(例:Visual Studio Code)
1. Flaskのインストール
まず、Flaskをインストールします。以下のコマンドをターミナルまたはコマンドプロンプトに入力してください。
pip install flask
2. Flaskアプリケーションの作成
Flaskアプリケーションの基本構造を作成します。以下のコードを app.py ファイルにコピーします。
from flask import Flask, render_template
import calendar
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def index():
# 現在の年と月を取得
now = datetime.now()
year = now.year
month = now.month
# カレンダーを作成
cal = calendar.Calendar(firstweekday=6)
month_days = cal.monthdayscalendar(year, month)
return render_template('calendar.html', year=year, month=month, month_days=month_days)
if __name__ == '__main__':
app.run(debug=True)
コードの説明
- Flask:Flaskクラスのインスタンスを作成します。
- @app.route('/'):ルートURLにアクセスした際に実行される関数を定義します。
- datetime.now():現在の年と月を取得します。
- calendar.Calendar(firstweekday=6):カレンダーの週の始まりを日曜日に設定します。
- monthdayscalendar(year, month):指定された年と月のカレンダーを2次元リストとして返します。
- render_template('calendar.html', ...):HTMLテンプレートをレンダリングし、カレンダーのデータを渡します。
3. HTMLテンプレートの作成
次に、HTMLテンプレートを作成します。プロジェクトディレクトリ内に templates フォルダを作成し、その中に calendar.html ファイルを作成します。以下のコードを calendar.html ファイルにコピーします。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>カレンダー</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
width: 14.28%; /* 7列なので100%を7で割る */
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>{{ year }}年{{ month }}月のカレンダー</h1>
<table>
<thead>
<tr>
<th>日</th>
<th>月</th>
<th>火</th>
<th>水</th>
<th>木</th>
<th>金</th>
<th>土</th>
</tr>
</thead>
<tbody>
{% for week in month_days %}
<tr>
{% for day in week %}
{% if day == 0 %}
<td></td>
{% else %}
<td>{{ day }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
コードの説明
- {{ year }}, {{ month }}:Pythonから渡された年と月の変数を表示します。
- {% for week in month_days %}:各週をループして行を作成します。
- {% for day in week %}:各日の値をチェックし、0の場合は空のセルを、それ以外の場合は日付を表示します。
4. アプリケーションの実行
すべてのファイルが揃ったら、以下のコマンドでアプリケーションを実行します。
python app.py
ブラウザで http://127.0.0.1:5000/ を開くと、現在の年と月のカレンダーが表示されます。
作成した画面
まとめ
今回は、PythonとHTMLを使ってシンプルなカレンダーアプリを作成しました。Flaskフレームワークを使用することで、動的なWebページを簡単に作成できることがわかりました。ぜひ自分のプロジェクトでも活用してみてください。