0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでFlaskを使って温度センサー表示

Posted at

新しいプロジェクトディレクトリを作成し、必要なファイルを作成していきましょう。まず、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 にアクセスすると、温度が表示されます。

temp28.jpg

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?