2026年5月13日 星期三

[水井USR] 自動更新水井USR網站上即時生態資料



 
水井USR網站:水井村USR|生態感測

範例一:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import requests

url = "https://shuijingusr.pythonanywhere.com/api/ecology/sensor-reading/"

data = {
    "token": "abc123",
    "water_quality": 7.1,
    "humidity": 70.0,
    "temperature": 29.5,
    "light": 42.0,
    "recorded_at": "2025-05-13T10:30:00+08:00"
}

try:
    response = requests.post(url, json=data, timeout=10)

    print("狀態碼:", response.status_code)

    try:
        print("回傳資料:")
        print(response.json())
    except ValueError:
        print("伺服器回傳不是 JSON:")
        print(response.text)

except requests.exceptions.RequestException as e:
    print("連線失敗:", e)


執行結果:
狀態碼: 201
回傳資料:
{'ok': True, 'message': '生態感測資料已成功寫入', 'data': {'id': 2, 'water_quality': 7.1, 'humidity': 70.0, 'temperature': 29.5, 'light': 42.0, 'status': 'normal', 'recorded_at': '2025-05-13T10:30:00+08:00'}}

範例二:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import time
import random
import requests
from datetime import datetime, timezone, timedelta

url = "https://shuijingusr.pythonanywhere.com/api/ecology/sensor-reading/"
taiwan_tz = timezone(timedelta(hours=8))

while True:
    now = datetime.now(taiwan_tz).isoformat()

    data = {
        "token": "abc123",
        "water_quality": round(random.uniform(7.0, 7.8), 1),
        "humidity": round(random.uniform(60.0, 75.0), 1),
        "temperature": round(random.uniform(28.0, 31.5), 1),
        "light": round(random.uniform(35.0, 55.0), 1),
        "recorded_at": now
    }

    try:
        response = requests.post(url, json=data, timeout=10)
        print("送出資料:", data)
        print("狀態碼:", response.status_code)
        print("回傳:", response.json())
        print("-" * 40)

    except requests.exceptions.RequestException as e:
        print("上傳失敗:", e)

    time.sleep(10)

執行結果:
送出資料: {'token': 'abc123', 'water_quality': 7.2, 'humidity': 60.9, 'temperature': 30.8, 'light': 37.8, 'recorded_at': '2026-05-13T21:33:30.885065+08:00'}
狀態碼: 201
回傳: {'ok': True, 'message': '生態感測資料已成功寫入', 'data': {'id': 12, 'water_quality': 7.2, 'humidity': 60.9, 'temperature': 30.8, 'light': 37.8, 'status': 'normal', 'recorded_at': '2026-05-13T21:33:30.885065+08:00'}}
----------------------------------------
送出資料: {'token': 'abc123', 'water_quality': 7.1, 'humidity': 66.7, 'temperature': 28.2, 'light': 42.6, 'recorded_at': '2026-05-13T21:33:42.168665+08:00'}
狀態碼: 201
回傳: {'ok': True, 'message': '生態感測資料已成功寫入', 'data': {'id': 13, 'water_quality': 7.1, 'humidity': 66.7, 'temperature': 28.2, 'light': 42.6, 'status': 'normal', 'recorded_at': '2026-05-13T21:33:42.168665+08:00'}}

沒有留言:

張貼留言