新しいプロジェクトディレクトリを作成し、必要なファイルを作成していきましょう。まず、temperature_serverというディレクトリを作成し、その中に必要なファイルを作成します。
以下のファイルを作成します:
app.py - メインのFlaskアプリケーション
requirements.txt - 必要なパッケージの依存関係
README.md - プロジェクトの説明
まず、app.pyを作成します:
app.py
from flask import Flask, render_template
import random # 実際のセンサーがない場合のダミーデータ用
app = Flask(__name__)
def get_temperature():
# ここに実際のセンサーからの読み取りコードを実装
# この例ではダミーデータを返します
return round(random.uniform(20, 30), 1)
@app.route('/')
def index():
temperature = get_temperature()
return render_template('index.html', temperature=temperature)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
次に、テンプレートディレクトリ(templates)とindex.htmlを作成します:
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>温度センサーモニター</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.container {
text-align: center;
padding: 2rem;
background-color: white;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.temperature {
font-size: 3rem;
color: #333;
}
.unit {
font-size: 1.5rem;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<h1>現在の温度</h1>
<div class="temperature">{{ temperature }}<span class="unit">°C</span></div>
</div>
</body>
</html>
最後に、requirements.txtを作成します:
requirements.txt
Flask==3.0.2
これで基本的なWebサーバーの準備が整いました。以下の手順で実行できます:
1.まず、必要なパッケージをインストールします:
pip install -r requirements.txt
2.サーバーを起動します:
python app.py
3.ブラウザで http://localhost:5000 にアクセスすると、温度が表示されます。