今天是第二十天我們可以寫一個k8s空氣品質資料庫管理系統,以下是我的程式碼
你可以使用 Python 的 FastAPI 或 Flask 來編寫後端 API,用於接收、存取空氣品質數據。以下是一個簡單的 FastAPI 範例。
from fastapi import FastAPI
from pydantic import BaseModel
import sqlite3
from datetime import datetime
app = FastAPI()
# 建立數據模型
class AirQualityData(BaseModel):
location: str
pm25: float
pm10: float
o3: float
no2: float
so2: float
co: float
timestamp: datetime
# 連接 SQLite 資料庫(可以換成 MySQL/PostgreSQL)
def get_db():
conn = sqlite3.connect('air_quality.db')
cursor = conn.cursor()
return conn, cursor
@app.on_event("startup")
def startup():
conn, cursor = get_db()
cursor.execute('''CREATE TABLE IF NOT EXISTS air_quality
(location TEXT, pm25 REAL, pm10 REAL, o3 REAL, no2 REAL,
so2 REAL, co REAL, timestamp TEXT)''')
conn.commit()
conn.close()
# 上傳空氣品質數據
@app.post("/air_quality/")
def create_air_quality(data: AirQualityData):
conn, cursor = get_db()
cursor.execute('''INSERT INTO air_quality (location, pm25, pm10, o3, no2, so2, co, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
(data.location, data.pm25, data.pm10, data.o3, data.no2, data.so2, data.co, data.timestamp))
conn.commit()
conn.close()
return {"message": "Data inserted successfully"}
# 查詢空氣品質數據
@app.get("/air_quality/{location}")
def get_air_quality(location: str):
conn, cursor = get_db()
cursor.execute("SELECT * FROM air_quality WHERE location = ?", (location,))
data = cursor.fetchall()
conn.close()
return {"data": data}
將應用容器化,以便能部署在 Kubernetes 上。
Dockerfile
:Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
requirements.txt
:fastapi
uvicorn
pydantic
sqlite3
docker build -t air_quality_api .
docker run -p 8000:8000 air_quality_api
接下來,你可以在 Kubernetes 上進行部署。建立一個 Deployment 和 Service。
apiVersion: apps/v1
kind: Deployment
metadata:
name: air-quality-deployment
spec:
replicas: 2
selector:
matchLabels:
app: air-quality
template:
metadata:
labels:
app: air-quality
spec:
containers:
- name: air-quality-container
image: air_quality_api:latest
ports:
- containerPort: 8000
apiVersion: v1
kind: Service
metadata:
name: air-quality-service
spec:
selector:
app: air-quality
ports:
- protocol: TCP
port: 80
targetPort: 8000
type: LoadBalancer
部署到 Kubernetes:
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
可以使用 Vue 或 React 設計簡單的查詢介面,通過 API 查詢並顯示數據。
import React, { useState, useEffect } from "react";
import axios from "axios";
function AirQualityDashboard() {
const [data, setData] = useState([]);
const [location, setLocation] = useState("");
const fetchData = async () => {
const result = await axios.get(`http://<API_URL>/air_quality/${location}`);
setData(result.data.data);
};
return (
<div>
<h1>Air Quality Dashboard</h1>
<input
type="text"
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="Enter location"
/>
<button onClick={fetchData}>Get Data</button>
<div>
{data.map((item, index) => (
<div key={index}>
<p>Location: {item[0]}</p>
<p>PM2.5: {item[1]}</p>
<p>PM10: {item[2]}</p>
<p>O3: {item[3]}</p>
<p>NO2: {item[4]}</p>
<p>SO2: {item[5]}</p>
<p>CO: {item[6]}</p>
<p>Timestamp: {item[7]}</p>
</div>
))}
</div>
</div>
);
}
export default AirQualityDashboard;
這段程式碼使用 FastAPI 框架來處理空氣品質數據的 REST API,包含數據的上傳和查詢功能。
from fastapi import FastAPI
from pydantic import BaseModel
import sqlite3
from datetime import datetime
class AirQualityData(BaseModel):
location: str
pm25: float
pm10: float
o3: float
no2: float
so2: float
co: float
timestamp: datetime
AirQualityData
類,描述了每次上傳的空氣品質數據,包含不同的污染物濃度和時間戳。def get_db():
conn = sqlite3.connect('air_quality.db')
cursor = conn.cursor()
return conn, cursor
這個函數用來建立與 SQLite 資料庫的連接,並返回資料庫連接物件和資料庫操作的游標。
@app.on_event("startup")
def startup():
conn, cursor = get_db()
cursor.execute('''CREATE TABLE IF NOT EXISTS air_quality
(location TEXT, pm25 REAL, pm10 REAL, o3 REAL, no2 REAL,
so2 REAL, co REAL, timestamp TEXT)''')
conn.commit()
conn.close()
air_quality
表格,儲存不同污染物的數據和時間戳。這個表只會在不存在時創建。@app.post("/air_quality/")
def create_air_quality(data: AirQualityData):
conn, cursor = get_db()
cursor.execute('''INSERT INTO air_quality (location, pm25, pm10, o3, no2, so2, co, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
(data.location, data.pm25, data.pm10, data.o3, data.no2, data.so2, data.co, data.timestamp))
conn.commit()
conn.close()
return {"message": "Data inserted successfully"}
@app.get("/air_quality/{location}")
def get_air_quality(location: str):
conn, cursor = get_db()
cursor.execute("SELECT * FROM air_quality WHERE location = ?", (location,))
data = cursor.fetchall()
conn.close()
return {"data": data}
要在 Kubernetes 上部署應用,首先需要將它容器化,這樣能使應用環境一致並便於管理。
Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
/app
。requirements.txt
複製到容器中。/app
目錄。fastapi
uvicorn
pydantic
sqlite3
這裡列出了應用所需的 Python 套件。
air_quality_api
的映像檔。這部分展示如何將容器化的應用部署到 Kubernetes 上。
apiVersion: apps/v1
kind: Deployment
metadata:
name: air-quality-deployment
spec:
replicas: 2
selector:
matchLabels:
app: air-quality
template:
metadata:
labels:
app: air-quality
spec:
containers:
- name: air-quality-container
image: air_quality_api:latest
ports:
- containerPort: 8000
air_quality_api
的 Docker 映像檔來建立容器。apiVersion: v1
kind: Service
metadata:
name: air-quality-service
spec:
selector:
app: air-quality
ports:
- protocol: TCP
port: 80
targetPort: 8000
type: LoadBalancer
這是簡單的前端程式碼,使用 React 建立一個介面來查詢空氣品質數據。
import React, { useState, useEffect } from "react";
import axios from "axios";
function AirQualityDashboard() {
const [data, setData] = useState([]);
const [location, setLocation] = useState("");
const fetchData = async () => {
const result = await axios.get(`http://<API_URL>/air_quality/${location}`);
setData(result.data.data);
};
return (
<div>
<h1>Air Quality Dashboard</h1>
<input
type="text"
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="Enter location"
/>
<button onClick={fetchData}>Get Data</button>
<div>
{data.map((item, index) => (
<div key={index}>
<p>Location: {item[0]}</p>
<p>PM2.5: {item[1]}</
p>
<p>PM10: {item[2]}</p>
<p>O3: {item[3]}</p>
<p>NO2: {item[4]}</p>
<p>SO2: {item[5]}</p>
<p>CO: {item[6]}</p>
<p>Timestamp: {item[7]}</p>
</div>
))}
</div>
</div>
);
}
export default AirQualityDashboard;
這個應用由 FastAPI 後端、Docker 容器化、Kubernetes 部署和簡單的 React 前端組成。後端提供空氣品質數據的儲存和查詢功能,容器化允許應用在不同環境中保持一致性,而 Kubernetes 提供了高可用性和可擴展性。