顯示具有 Mapleboard 標籤的文章。 顯示所有文章
顯示具有 Mapleboard 標籤的文章。 顯示所有文章

2026年8月18日 星期二

高 CP 值的 Debian Linux 微型電腦 MP520-20

前陣子在評估適合跑 OpenClaw 的機器時, 找到下面這塊開發板 MP520-20 :





這是我的 Mapleboard MP-510 的升級版, 性能強大許多 (價格近兩倍), 搭載了 Rockchip RK3588S 八核處理器 (4× Cortex-A76 @ 2.4GHz + 4× Cortex-A55 @ 1.8GHz), 8GB LPDDR4X 與 128GB NVMe SSD, 出廠預裝了中文環境的 Debian Linux, 產品定位主要是做為高效能的微型電腦 (Mini PC/Linux 工作站), 低功耗桌機, 或邊緣伺服器 (配備 26-pin 擴充 I/O 與 UART 介面).

此微型電腦非常適合跑 OpenClaw, 作為開源的個人 AI  代理 (Agent) 網關, CPU 運算力約為 Pi 4 的 3~4 倍, 8GB RAM 對於運行 OpenClaw 及相關工具 (如網頁爬蟲, 檔案讀寫, 自動化腳本) 來說綽綽有餘, 而內建 128GB NVMe SSD 高速低功耗, 很適合作為全年無休 (24/7) 的龍蝦伺服器, 性能上完全輾壓 Pi 4. 雖然 Pi 4 裸板較便宜, 但加購散熱外殼, 變壓器與 128GB 高速 MicroSD 後價差其實不大, 比起一體成型的 MP520-20 來說 CP 值不高. 

總之, 與 Pi 4 相比, MP520-20 強悍的 RK3588S (4大核A76 + 4小核A55) 與板載 128GB NVMe SSD 不僅解決了樹莓派 MicroSD 卡容易因頻繁讀寫損壞的痛點 (NVMe 隨機讀寫速度遠勝 MicroSD,  在 OpenClaw 頻繁讀寫本地記憶時會較順暢且不易讀寫錯誤); 兩者在執行網頁爬蟲, 無頭瀏覽器與多工 Agent 任務時的效能差距非常巨大. 

不過, MP520-20 的 GPU 為 ARM Mali-G610 MP4, 支援 OpenCL / Vulkan / OpenGL 但不支援 CUDA, 而主流的開源 LLM 生態如 vLLM 與 llama.cpp 等 GPU 加速高度依賴 NVIDIA CUDA, 因此 Mali GPU 派不上用場, 無法支援本地大模型推論, 只能使用 CPU 推論, 其 8 核 CPU 跑 llama.cpp 運行 1.5B~3B 的小型量化模型還可以, 跑 7B 模型生成速度會很慢 (約 4~6 tokens/s). 

如果用 MP520-20 來跑 OpenClaw 養龍蝦的話, 最好是將 MP520-20 作為 OpenClaw Agent 閘道與執行端, 大模型思考推理部分就串接雲端 API (例如 OpenAI, Claude, 或 Gemini), 如果用 CPU 去跑本地的小型量化模型效能不佳. 

2026年7月19日 星期日

Google Antigravity 學習筆記 : 重構 serverless 函式執行平台 (五)

經過前面的測試已驗證了重構後的程式碼基本上達成了讓平台具備 API Key 功能的目標, 在提交到 GitHub 之前, 想要先佈署到 Mapleboard 上更新 serverless 到具有 API Key 功能的最新版. 關於 Mapleboard 筆記參考 :


本系列全部文章索引參考 :



7. 在 Mapleboard 佈署新版 serverless : 

先用 VNC Cloud 遠端連線到 Mapleboard 桌面, 開啟終端機, 切換到 serverless 專案目錄下, 用 zip 指令把整個專案除指定之敏感檔案外全部壓縮成 zip 檔 : 

tony1966@LX2438:~/flask_apps/serverless$ zip -r serverless_v4.zip . -x "serverless.db" "serverless_error.log" "*.pyc" "__pycache__/*" ".env"

參數 -r 表示要遞迴壓縮, 即連同所有子資料夾 (如 functions/) 一起打包. serverless_backup.zip 是壓縮結果的檔檔名. 後面的 . . 代表壓縮當前目錄下的所有東西, -x 參數後面接的是排除 (不壓縮) 名單, 這裡排除了本地資料庫 (serverless.db), 日誌檔 (serverless_error.log), Python 快取檔, 以及含有敏感密碼的 .env 檔. 

然後用 WinSCP 連線 Mapleboard, 注意, 之前安裝 fail2ban 時為了提升資安, 已修改 SSH 埠 (不再是預設的 22), 埠號可用下列指令查得 :

tony1966@LX2438:~/flask_apps/serverless$ sudo nano /etc/fail2ban/jail.local  

設定 WinSCP 連線時除了要輸入固定 IP 外, 還要更改 SSH 埠號, 如果用 22 埠是無法連線的. 連線成功後, 先將上面備份的 zip 檔傳送至本地保存. 完成後將本地的 serverless.py 主程式與 functions 資料夾上傳到 Mapleboard 的 serverless 專案目錄下覆蓋舊版程式檔. 

由於主程式 serverless.py 有更改, 所以須用下例指令重啟服務才會運行新版程式 :

tony1966@LX2438:~/flask_apps/serverless$ sudo systemctl restart serverless

用瀏覽器測試 hello.py 函式 : 





在有登入情況下, 對函式的請求無需攜帶 API Key 即可順利執行;  如果沒有登入就會收到 401 錯誤, 例如 :



但修改前一篇的 deploy.py 的 URL 想要進行本地佈署 hello.py 卻出現連線異常與 404 等錯誤, 經查原來我的 Mapleboard 之前在架站時 Nginx 與站台 (主要是 hello 站台與 flask.tony1966.cc) 設定出現埠的衝突, 重啟 Nginx 出現 2~3 個 warning. 經過與 Gemini 討論後, 修改站台設定後終於解決此問題, Nginx 設定檔就徹底理順了, 摘要如下 : 
  • reject_ip 盡職地守在大門口擋掉所有奇奇怪怪的 IP 掃描.
  • flask.tony1966.cc 安全地走 HTTPS 連線, 讓新版 Serverless 平台, 樹莓派爬蟲與電腦部署都能順暢通訊. 
  • hello 站台也成功轉型, 乾乾淨淨地留在 443 埠當作你的 is_alive 測試通道 (Port 8080/8081).
站台清單檢視指令 : ls -l /etc/nginx/sites-enabled/
重啟 Nginx 伺服器指令 : sudo nginx -t
重新載入 Nginx 指令  : sudo systemctl reload nginx

佈署程式 deploy.py 的 URL 要改成 https://flask.tony1966.cc, 下面是佈署市圖爬蟲伺服端程式 update_ksml_books.py 的範例 (伺服端程式都不必為 serverless 升版做任何改變) : 

SERVER_URL="https://flask.tony1966.cc"
API_TOKEN="your-api-key"

# 2. 定義要佈署的函式名稱與本地檔案路徑
TARGET_FUNCTION_NAME="update_ksml_books"
LOCAL_FILE_PATH="update_ksml_books.py"

再次執行 deploy.py 就順利將函式發佈到 serverless 平台上了 :

D:\python\test>python deploy.py  
🚀 正在將 update_ksml_books.py 更新至 https://flask.tony1966.cc...
✅ 函式更新成功!
伺服器回應: {'func_name': 'update_ksml_books', 'message': '模組 update_ksml_books 已成功更新'}

deploy.py 的完整內容如下 :

# deploy.py
import os
import requests

# 1. 設定伺服器資訊與 API Token
# 地端測試可用 http://127.0.0.1:5000,上雲端後改成你的 Render 網址
SERVER_URL="https://flask.tony1966.cc"
API_TOKEN="your-api-key"

# 2. 定義要佈署的函式名稱與本地檔案路徑
TARGET_FUNCTION_NAME="update_ksml_books"
LOCAL_FILE_PATH="update_ksml_books.py"

def function_exists(func_name):
    """檢查遠端伺服器上的函式是否已存在(透過 GET 探測)"""
    url=f"{SERVER_URL}/function/{func_name}"
    headers={"X-API-Key": API_TOKEN}
    try:
        response=requests.get(url, headers=headers)
        # 404 表示不存在,其他狀態(200/400/500)表示檔案存在
        return response.status_code != 404
    except requests.exceptions.RequestException:
        return False  # 連線失敗時保守假設不存在

def deploy_function():
    # 檢查本地檔案是否存在
    if not os.path.exists(LOCAL_FILE_PATH):
        print(f"❌ 找不到本地檔案: {LOCAL_FILE_PATH}")
        return
    # 讀取本地最新的程式碼內容
    with open(LOCAL_FILE_PATH, "r", encoding="utf-8") as f:
        new_code=f.read()

    headers={
        "X-API-Key": API_TOKEN,
        "Content-Type": "application/json"
    }
    payload={
        "func_name": TARGET_FUNCTION_NAME,
        "code": new_code
    }

    # 3. 自動判斷:函式已存在 → update,不存在 → save(新增)
    if function_exists(TARGET_FUNCTION_NAME):
        url=f"{SERVER_URL}/function/update_function"
        action="更新"
    else:
        url=f"{SERVER_URL}/function/save_function"
        action="新增"

    print(f"🚀 正在將 {LOCAL_FILE_PATH} {action}至 {SERVER_URL}...")
    try:
        response=requests.post(url, json=payload, headers=headers)
        # 新增成功是 201,更新成功是 200
        if response.status_code in (200, 201):
            print(f"✅ 函式{action}成功!")
            print("伺服器回應:", response.json())
        else:
            print(f"❌ {action}失敗 (狀態碼: {response.status_code})")
            try:
                print("錯誤原因:", response.json())
            except ValueError:
                print("非 JSON 回應內容:", response.text)
    except requests.exceptions.RequestException as e:
        print(f"💥 連線發生異常: {e}")

if __name__ == "__main__":
    deploy_function()

市圖爬蟲程式本機版則需要配合 serverless 添加 API Key 功能而升版, 否則請求都會被 401 拒絕, 這部分記在另一篇. 

2026年6月13日 星期六

Mapleboard MP510-50 測試 (四十四) : 設定 PPPoE 自動撥接上網

上周可能因為雷雨使市電瞬斷, 鄉下老家的 Mapleboard 主機應該有重開機, 它是用網路線直接連線光世代數據機, 以撥接方式連線上網, 印象中當時設定 pppoe 時有設開機自動連線, 不知為何這次失靈. 早上花了一點時間才重新設定好, 以下紀錄這次查修過程. 之前的設定參考 :


本系列全部文章參考 :


首先檢查網路連線狀態 : 

tony1966@LX2438:~$ ifconfig  
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.102  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::66c7:6bea:e03e:ef60  prefixlen 64  scopeid 0x20<link>
        ether 16:72:2e:da:e7:3c  txqueuelen 1000  (Ethernet)
        RX packets 12  bytes 1961 (1.9 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 192  bytes 19933 (19.9 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 14  

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 356  bytes 27782 (27.7 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 356  bytes 27782 (27.7 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

沒有出現 ppp0, 表示並未撥接上網, 可能是因為非預期斷電導致 NetworkManager 服務毀損, 設定檔異常, 或是原本設定的 autoconnect (自動連線) 屬性跑掉, 先重啟 NetworkManager 服務 : 

tony1966@LX2438:~$ sudo systemctl restart NetworkManager   

檢查服務狀態, 確認 NetworkManager 顯示為 active (running) 狀態 :

tony1966@LX2438:~$ sudo systemctl status NetworkManager   
● NetworkManager.service - Network Manager
     Loaded: loaded (/lib/systemd/system/NetworkManager.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2026-06-11 14:34:45 CST; 15s ago
       Docs: man:NetworkManager(8)
   Main PID: 33100 (NetworkManager)
      Tasks: 4 (limit: 4213)
     Memory: 3.4M
        CPU: 295ms
     CGroup: /system.slice/NetworkManager.service
             └─33100 /usr/sbin/NetworkManager --no-daemon

用 NetworkManager 的指令工具 nmcli 指令來檢視之前建立的 PPPoE 連線 : 

tony1966@LX2438:~$ nmcli connection show   
NAME             UUID                                  TYPE      DEVICE 
Ifupdown (eth0)  681b428f-beaf-8932-dce4-687ed5bae28e  ethernet  eth0   
EDIMAX-tony      ddebdded-8805-4631-aa85-f08c412404bf  wifi      --     
hinet            a857fb4d-b2c2-43e2-a43f-a30a30def74f  pppoe     --     
hinet            62250a6d-dc03-44b9-be71-7179ce1ec6c9  pppoe     --     
TonyNote8        37db6693-372b-4190-a4d0-c71aef40bc38  wifi      --     

其中 hinet 就是之前用來撥接上網的 PPPoE 連線, 這兩個連線的名稱雖然一樣, 但它們的 UUID (唯一識別碼) 完全不同, 這很有可能就是無法自動撥接上網的元兇, 因為當系統開機準備自動連線時, 它看到兩個都叫 hinet 的設定檔, NetworkManager 可能會不知道該用哪一個, 或者其中一個是壞掉的舊設定, 系統卻偏偏去讀到壞的那一個導致自動撥接失敗. 

由於不知哪個 UUID 才是可正常連線的設定, 所以最乾淨的做法是把這兩個同名為 hinet 的連線設定都刪除, 重新建立一個乾淨的連線設定 : 

ony1966@LX2438:~$ nmcli connection delete uuid a857fb4d-b2c2-43e2-a43f-a30a30def74f   
連線「hinet」 (a857fb4d-b2c2-43e2-a43f-a30a30def74f) 已成功刪除。

tony1966@LX2438:~$ nmcli connection show 
NAME             UUID                                  TYPE      DEVICE 
Ifupdown (eth0)  681b428f-beaf-8932-dce4-687ed5bae28e  ethernet  eth0   
EDIMAX-tony      ddebdded-8805-4631-aa85-f08c412404bf  wifi      --     
hinet            62250a6d-dc03-44b9-be71-7179ce1ec6c9  pppoe     --     
TonyNote8        37db6693-372b-4190-a4d0-c71aef40bc38  wifi      --     

刪除第二個 hinet 連線設定 : 

tony1966@LX2438:~$ nmcli connection delete uuid 62250a6d-dc03-44b9-be71-7179ce1ec6c9  
連線「hinet」 (62250a6d-dc03-44b9-be71-7179ce1ec6c9) 已成功刪除。

檢視連線清單已無 hinet 了 : 

tony1966@LX2438:~$ nmcli connection show  
NAME             UUID                                  TYPE      DEVICE 
Ifupdown (eth0)  681b428f-beaf-8932-dce4-687ed5bae28e  ethernet  eth0   
EDIMAX-tony      ddebdded-8805-4631-aa85-f08c412404bf  wifi      --     
TonyNote8        37db6693-372b-4190-a4d0-c71aef40bc38  wifi      --     

建立新的 PPPoE 撥接連線 :

tony1966@LX2438:~$ sudo nmcli connection add type pppoe con-name "hinet" ifname eth0 username "光世代帳號@ip.hinet.net" password "老家電話號碼"   
[sudo] tony1966 的密碼: 
連線「hinet」 (edf0fefa-d122-4d62-88bd-5a9cc085830a) 已成功新增。

檢視連線清單新的 hinet 連線已 :  

tony1966@LX2438:~$ nmcli connection show  
NAME             UUID                                  TYPE      DEVICE 
Ifupdown (eth0)  681b428f-beaf-8932-dce4-687ed5bae28e  ethernet  eth0   
EDIMAX-tony      ddebdded-8805-4631-aa85-f08c412404bf  wifi      --     
hinet            edf0fefa-d122-4d62-88bd-5a9cc085830a  pppoe     --     
TonyNote8        37db6693-372b-4190-a4d0-c71aef40bc38  wifi      --     

用下列指令設定開機自動用此連線設定撥接上網 : 

tony1966@LX2438:~$ nmcli connection modify id "hinet" connection.autoconnect yes

手動用 hinet 連線撥接上網 : 

tony1966@LX2438:~$ nmcli connection up id "hinet"   
連線已成功啟用(D-Bus 啟用路徑:/org/freedesktop/NetworkManager/ActiveConnection/4)
tony1966@LX2438:~$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        ether 16:72:2e:da:e7:3c  txqueuelen 1000  (Ethernet)
        RX packets 95413  bytes 73056382 (73.0 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 490867  bytes 54678967 (54.6 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 14  

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 262801  bytes 19744911 (19.7 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 262801  bytes 19744911 (19.7 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ppp0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1492
        inet 220.133.1x.1yy  netmask 255.255.255.255  destination 168.95.98.254
        inet6 2001:b011:c002:44b:20dd:96c1:295d:93a9  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::4948:3225:47ee:c1ee  prefixlen 64  scopeid 0x20<link>
        inet6 2001:b011:c002:44b:ca70:4579:c7c2:10f9  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::2eab:a3ae:c3d2:2ad5  prefixlen 64  scopeid 0x20<link>
        ppp  txqueuelen 3  (Point-to-Point Protocol)
        RX packets 121  bytes 40452 (40.4 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 157  bytes 26014 (26.0 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

出現 ppp0 網路連線表示已連網成功, 開啟瀏覽器可正常瀏覽網頁, 重新啟動系統確定重開機會自動撥接上網, 終於讓主機與網站重新恢復運作. 

2025年10月19日 星期日

Mapleboard MP510-50 測試 (四十三) : HTTP API 函式執行平台 (7)

這幾天為了給市圖爬蟲程式改版 (爬取結果儲存於資料庫), 將架在 Mapleboard 與 render.com 上面 serverless 平台添加了 SQLite 資料庫線上管理功能, 本篇旨在紀錄此新增功能. 關於 SQLite 資料庫操作參考 :


在之前的 serverless 專案中, 利用一個 SQLite 資料庫 serverless.db 來儲存各個非系統函式模組被呼叫的次數, 資料表名稱為 call_stats. 現在想用這資料庫來儲存應用函式的資料, 例如圖書館爬蟲之爬取結果, 所以需要一組系統函式來進行資料表的線上管理, 為此我在首頁函式列表底下添加了一個 "資料表列表" 超連結至 /function/list_tables : 



所需模組如下 :
  1. list_tables.py :
    資料表管理之首頁, 以表格顯示非系統資料表, 利用超連結進行顯示 schema, 紀錄, 執行 SQL, 以及刪除資料表等操作. 
  2. add_table.py :
    根據 Schema 新增一個資料表.
  3. drop_table.py :
    刪除指定之資料表.
  4. view_table.py :
    以分頁方式顯示指定之資料表內容.
  5. show_shema.py :
    顯示指定資料表結構.
  6. export_table.py :
    輸出指定資料表內容為 csv 檔. 
  7. execute_sql.py :
    執行 SQL 指令. 
我透過 ChatGPT 協助快速生成上述 7 個資料庫操作的程式碼, 然後依據需求進行微幅調整. 在這過程中也發現了 edit_function.py 的臭蟲, 由於線上操作需要顯示較複雜之 HTML 碼, 原本的 edit_function.py 頁面會出現如下版面崩潰現象 : 




解決之道是使用 html.escape 函式來跳脫 HTML 碼 (例如將 < 字元轉成 &lt;). 注意, 以前 Flask 有實作 escape() 函式, 但新版因 Python 標準模組 html 模組已內建而移除. 修改後的 edit_function.py 程式碼如下 : 

# edit_function.py
# 模組名稱也可更改 -> 相當於新增模組
from flask import render_template_string
import os
from html import escape

def main(request, **kwargs):
    module_name=request.args.get('module_name', '')  # 取得模組名稱
    if not module_name:  # 檢查有無傳入模組名稱
        return '請指定要編輯的模組名稱,格式 ?module_name=hello'
    filename=f'./functions/{module_name}.py'
    if not os.path.isfile(filename):
        return f'找不到函式檔案:{module_name}'
    with open(filename, 'r', encoding='utf-8') as f: 
        content=f.read()  # 讀取模組內容
        content=escape(content)
    html=f'''
    <h2>編輯函式模組:/functions/{module_name}.py</h2>
    <form method="POST" action="/function/update_function">
        <label>模組名稱(請用英數字,不含副檔名 .py):</label><br>    
        <input type="text" name="module_name" size="50" value="{module_name}"><br><br>
        <label>模組內容(請輸入合語法的 Python 程式碼):</label><br>        
        <textarea id="code" name="code" rows="20" cols="100" style="font-family:monospace;">{content}</textarea><br><br>
        <button type="button" onclick="location.href='/function/list_functions'">取消</button>
        <button type="button" onclick="document.getElementById('code').value = '';">清除</button>
        <button type="submit">更新</button>
    </form>
    '''
    return render_template_string(html)

此處改用 flask.render_template_string() 函式來渲染 HTML 程式碼.

以下是經過修正後的程式碼 :


1. list_tables.py :

此模組為資料表管理之首頁, 以表格顯示所有非系統資料表, 利用超連結進行顯示 schema, 紀錄, 執行 SQL, 以及刪除資料表等操作.

# list_tables.py
import os
import sqlite3

def main(request, **kwargs):    
    protected=[]  # 被保護的資料名稱清單 (不顯示)    
    DB_PATH='./serverless.db'  # 資料庫路徑
    # 檢查資料庫檔案是否存在
    if not os.path.exists(DB_PATH):
        html='''
            <p>資料庫檔案 serverless.db 不存在!
            <a href="/function/list_functions">函式列表</a></p>
            '''
        return html
    # 連線資料庫
    try:
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 取得所有非系統資料表
        cur.execute("""
            SELECT name FROM sqlite_master WHERE type='table'
            AND name NOT LIKE 'sqlite_%' ORDER BY name;
            """)
        rows=cur.fetchall()
        tables=[r[0] for r in rows]
        html='<h2>資料表列表</h2>'
        html += '<table border="1" cellspacing="0" cellpadding="6" '+\
                'style="border-collapse: collapse;">'
        html += '<tr><th>資料表名稱</th><th>記錄筆數</th><th>Schema</th>' +\
                '<th>檢視記錄</th><th>匯出</th><th>刪除</th></tr>'
        if not tables:
            html += '<tr><td colspan="6">目前無任何資料表</td></tr>'
        else:  # 遍歷所有非系統資料表
            for table in tables:
                if table in protected:  # 不顯示被保護資料表                    
                    continue                
                try:  # 取得該資料表的記錄筆數 (若失敗則顯示 '-')
                    cur2=conn.cursor()
                    cur2.execute(f"SELECT COUNT(*) FROM \"{table}\";")
                    cnt=cur2.fetchone()[0]
                except Exception:  # 資料表無紀錄
                    cnt='-'
                html += '<tr>'
                html += f'<td>{table}</td>'
                html += f'<td align="right">{cnt}</td>'
                html += f'<td><a href="/function/show_schema?table={table}">顯示</a></td>'
                html += f'<td><a href="/function/view_table?table={table}">檢視</a></td>'
                html += f'<td><a href="/function/export_table?table={table}">CSV</a></td>'
                html += f'<td><a href="/function/drop_table?table={table}" onclick=' +\
                        f'"return confirm(\'確定要刪除資料表 {table} 嗎?\')">刪除</a></td>'
                html += '</tr>'
        html += '</table>'
        # 管理連結:新增資料表、回到主頁、登出等
        html += '<br><a href="/function/add_table">新增資料表</a> '
        html += '<a href="/function/execute_sql">執行 SQL</a> '
        html += '<a href="/function/list_functions">返回函式列表</a> '
        html += '<a href="/logout">登出</a>'
        conn.close()
        return html
    except sqlite3.Error as e:
        return f'<p>連線資料庫失敗 {str(e)}</p>'
    finally:
        if 'conn' in locals():
            conn.close()    

此處 protected 用來列舉系統資料表, 避免在操作中被誤改, 目前僅統計呼叫次數 call_stats 資料表而已, 為了測試方便先暫時維持空串列, 測試完再把 call_stats 加入串列中. 




所有資料庫操作的功能都在此網頁中. 


2. add_table.py :

此模組根據指定之 Schema 新增一個資料表.

# add_table.py
import os
import sqlite3
from flask import request

def main(request, **kwargs):
    DB_PATH='./serverless.db'
    # 還沒送出表單 : 顯示建立表單頁面
    if request.method == 'GET':
        html=(
            "<h2>新增資料表</h2>"
            "<form method='post' action='/function/add_table'>"
            "<label>資料表名稱:</label><br>"
            "<input type='text' name='table' required><br><br>"
            "<label>欄位定義 (Schema, 以逗號分隔):</label><br>"
            "<textarea name='schema' rows='4' cols='70' "
            "placeholder='例如:id INTEGER PRIMARY KEY, name TEXT, age INTEGER, height REAL' "
            "required></textarea><br><br>"
            "<input type='submit' value='建立資料表'>"
            "</form>"
            "<a href='/function/list_tables'>返回資料表列表</a>"
            )
        return html
    # 處理表單送出
    if request.method == 'POST':
        table=request.form.get('table', '').strip()
        schema=request.form.get('schema', '').strip()
        if not table or not schema:
            return '<p>請輸入資料表名稱與欄位定義!<a href="/function/add_table">返回</a></p>'
        if not os.path.exists(DB_PATH):
            return '''
                <p>資料庫檔案 serverless.db 不存在!
                <a href="/function/list_tables">返回</a></p>
                '''
        try: # 建立資料表
            conn=sqlite3.connect(DB_PATH)
            cur=conn.cursor()
            cur.execute(f'CREATE TABLE IF NOT EXISTS "{table}" ({schema});')
            conn.commit()
            conn.close()
            return f'''
                <p>資料表 <b>{table}</b> 建立成功!</p>
                <a href="/function/list_tables">返回資料表列表</a>
                '''
        except sqlite3.Error as e:
            return f'<p>建立資料表失敗:{str(e)} <a href="/function/add_table">返回</a></p>'
        finally:
            if 'conn' in locals():
                conn.close()            

此模組集輸入表單與建立資料表兩個動作於一身, 依據 HTTP 方法來判定要做哪個動作, 剛進入 /function/add_table 時是 GET 方法, 這時會顯示輸入表單頁面 : 




此處以建立市圖借書預約資訊的資料表 ksml_books 為例, 輸入如下 Schema :

account PRIMARY KEY, borrow_books TEXT, reserve_books TEXT, updated_at TEXT 

按建立資料表按鈕會以 POST 方法再次請求 /function/add_table, 這時會執行 CREATE TABLE 指令建立資料表 : 




按 ksml_books 資料表 Schema 欄的顯示鈕會請求 /function/show_schema 模組, 其程式碼如下 :

# show_schema.py
import os
import sqlite3
from urllib.parse import parse_qs

def main(request, **kwargs):
    # 解析 URL 參數取得資料表名稱
    query=request.query_string.decode('utf-8')
    params=parse_qs(query)
    table=params.get('table', [''])[0]
    DB_PATH='./serverless.db'
    # 檢查資料庫是否存在
    if not os.path.exists(DB_PATH):
        return '''
        <p>資料庫檔案 serverless.db 不存在!
        <a href="/function/list_tables">返回資料表列表</a></p>
        '''
    # 檢查 URL 參數中是否有 table 名稱
    if not table:
        return '''
        <p>缺少 table 參數!
        <a href="/function/list_tables">返回資料表列表</a></p>
        '''
    try:
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 檢查資料表是否存在
        cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;", (table,))
        exists=cur.fetchone()
        if not exists:
            conn.close()
            return f'''
            <p>資料表 <b>{table}</b> 不存在!
            <a href="/function/list_tables">返回資料表列表</a></p>
            '''
        # 取得欄位資訊
        cur.execute(f"PRAGMA table_info('{table}');")
        columns=cur.fetchall()
        # 取得 Schema 的 SQL
        cur.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?;", (table,))
        create_sql=cur.fetchone()[0]
        conn.close()
        # 產生 HTML
        html=f'<h2>資料表 {table} 結構 (Schema)</h2>'
        html += '<table border="1" cellspacing="0" cellpadding="6" style="border-collapse: collapse;">'
        html += '<tr><th>#</th><th>欄位名稱</th><th>資料型別</th><th>非空</th><th>預設值</th><th>主鍵</th></tr>'
        for col in columns:
            cid, name, ctype, notnull, dflt_value, pk=col
            html += f'<tr>'
            html += f'<td>{cid}</td>'
            html += f'<td>{name}</td>'
            html += f'<td>{ctype}</td>'
            html += f'<td>{"✓" if notnull else ""}</td>'
            html += f'<td>{dflt_value if dflt_value is not None else ""}</td>'
            html += f'<td>{"✓" if pk else ""}</td>'
            html += '</tr>'
        html += '</table>'
        # 顯示 CREATE TABLE 語法
        html += '<h3>CREATE TABLE SQL 語法</h3>'
        html += f'<pre style="background-color:#f4f4f4;padding:10px;">{create_sql}</pre>'
        # 導覽連結
        html += '<a href="/function/list_tables">返回資料表列表</a>'
        return html
    except sqlite3.Error as e:
        return f'<p>讀取資料表結構失敗:{str(e)}</p>'
    finally:
        if 'conn' in locals():
            conn.close()

此程式使用 urllib.parse.parse_qs() 函式來解析請求之 URL 字串以取得 table 參數, 先用 PRAGMA table_info('{table}') 指令取得資料表的欄位資訊, 然後從 SQLite 的系統資料表 sqlite_master 的 sql 欄位中取得建立此資料表之 SQL 指令, 最後利用迴圈顯示欄位資訊與 Schema (SQL 指令) :




接下來實作 /function/execute_sql 並利用它來寫入資料表 :

# execute_sql.py
import os
import sqlite3
from flask import request
from html import escape   

def main(request, **kwargs):
    DB_PATH='./serverless.db'
    # 還沒送出表單 (GET):顯示 SQL 輸入頁面
    if request.method == 'GET':
        html=(
            "<h2>執行 SQL 指令</h2>"
            "<form method='post' action='/function/execute_sql'>"
            "<label>輸入 SQL 指令:</label><br>"
            "<textarea name='sql' rows='6' cols='80' "
            "placeholder='例如:SELECT * FROM call_stats;' required></textarea><br><br>"
            "<input type='submit' value='執行'>"
            "</form>"
            "<a href='/function/list_tables'>返回資料表列表</a>"
        )
        return html  # Removed conn.close() since conn is not defined
    # 處理表單送出 (POST):執行 SQL 指令
    if request.method == 'POST':
        sql=request.form.get('sql', '').strip()  # 取出 sql 欄位
        if not sql:
            return '<p>請輸入 SQL 指令!<a href="/function/execute_sql">返回</a></p>'
        if not os.path.exists(DB_PATH):
            return (
                '<p>資料庫檔案 serverless.db 不存在!'
                '<a href="/function/list_tables">返回</a></p>'
            )
        try:  # 執行 SQL 指令 
            conn=sqlite3.connect(DB_PATH)  # 建立連線與 cursor
            cur=conn.cursor()
            # SELECT 查詢 : 執行查詢後取出所有結果
            if sql.lower().startswith('select'):
                cur.execute(sql)
                rows=cur.fetchall()
                columns=[desc[0] for desc in cur.description]  # 取得欄位名稱
                # 將查詢結果轉成 HTML 表格
                if not rows:
                    result="<p>查無資料。</p>"
                else:
                    result='<table border="1" cellspacing="0" cellpadding="6" style="border-collapse: collapse;">'
                    result += "<tr>" + "".join(f"<th>{escape(col)}</th>" for col in columns) + "</tr>"
                    for row in rows: 
                        result += "<tr>" + "".join(f"<td>{escape(str(v))}</td>" for v in row) + "</tr>"
                    result += "</table>"
                conn.close()  # 關閉資料庫連線
                return (
                    f"<h2>SQL 查詢結果</h2>"
                    f"<p><b>指令:</b> {escape(sql)}</p>"
                    f"{result}"
                    "<br><a href='/function/execute_sql'>返回</a>"
                )
            else:  # 其他非 SELECT 指令 (INSERT, UPDATE, DELETE, DROP/CREATE TABLE) 
                cur.execute(sql)
                conn.commit()
                affected=cur.rowcount
                conn.close()
                return (
                    f"<p>SQL 指令執行成功!(影響 {affected} 筆紀錄)</p>"
                    f"<p><b>指令:</b> {escape(sql)}</p>"
                    "<a href='/function/execute_sql'>返回</a>"
                )
        except sqlite3.Error as e:
            conn.close()  # 關閉資料庫連線
            return f"<p>SQL 執行錯誤:{escape(str(e))}</p><a href='/function/execute_sql'>返回</a>"

此程式與 create_table.py 結構相同, 都是利用判別 HTTP 請求是 GET 或 POST 方法來決定回應方式, 若是 GET 方法就回應一個 SQL 輸入頁面; 若是 POST 方法就執行表單傳來的 SQL 指令 (分成 SELECT 與非 SELECT 指令兩類). 另外, 與上面修改 edit_function.py 的原因一樣, 為了避免網頁版面崩掉與 XSS 注入, 此程式使用 html.escape() 來跳脫 HTML 字元. 

第一次請求 /function/execute_sql 時是 GET 方法, 這時會顯示 SQL 輸入頁面, 測試用的 SQL 寫入指令例如 : 

INSERT OR REPLACE INTO ksml_books (account, borrow_books, reserve_books, updated_at)
VALUES ('tony', '["Python入門", "資料庫設計"]', '["AI導論"]', '2025-10-19 14:39:00')

此處因為 account 是不能重複的主鍵, 所以我們使用 INSERT OR REPLACE 指令, 當然也可以第一次用 INSERT 後續用 UPDATE 指令, 但 用 INSERT OR REPLACE 較單純 :





新增紀錄成功後, 再新增下一筆紀錄 : 

INSERT OR REPLACE INTO ksml_books (account, borrow_books, reserve_books, updated_at)
VALUES ('amy', '["京都時光"]', '["關西地圖"]', '2025-10-19 14:45:00')

這樣回到資料表列表就會看到 ksml_stats 有兩筆紀錄了 :




按檢視紀錄欄中的檢視超連結就會呼叫 /function/view_table 顯示資料表內容, 程式碼如下 :

# view_table.py
import os
import sqlite3
import html
from urllib.parse import parse_qs

def main(request, **kwargs):
    # 解析 URL 查詢參數 (?table=xxx&page=1)
    query=request.query_string.decode('utf-8')
    params=parse_qs(query)
    table=params.get('table', [''])[0]
    try:
        page=int(params.get('page', ['1'])[0])
        if page < 1:
            page=1
    except ValueError:
        page=1    
    DB_PATH='./serverless.db'
    ROWS_PER_PAGE=50  # 每頁顯示筆數
    # 檢查資料庫是否存在
    if not os.path.exists(DB_PATH):
        return '''
        <p>資料庫檔案 serverless.db 不存在!
        <a href="/function/list_tables">返回資料表列表</a></p>
        '''
    # 檢查 URL 參數中是否有 table 名稱
    if not table:
        return '''
        <p>缺少 table 參數!
        <a href="/function/list_tables">返回資料表列表</a></p>
        '''
    try:
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 安全檢查 (避免惡意表名注入)
        cur.execute("""
            SELECT name FROM sqlite_master
            WHERE type='table' AND name=?
        """, (table,))
        if not cur.fetchone():
            conn.close()
            return f'<p>資料表 "{html.escape(table)}" 不存在!</p>'
        # 取得欄位名稱
        cur.execute(f'SELECT * FROM "{table}" LIMIT 1;')
        colnames=[d[0] for d in cur.description] if cur.description else []
        # 計算總筆數
        cur.execute(f'SELECT COUNT(*) FROM "{table}";')
        total_rows=cur.fetchone()[0]
        total_pages=(total_rows + ROWS_PER_PAGE - 1) // ROWS_PER_PAGE
        # 取得當前頁的資料
        offset=(page - 1) * ROWS_PER_PAGE
        cur.execute(f'SELECT * FROM "{table}" LIMIT ? OFFSET ?;', (ROWS_PER_PAGE, offset))
        rows=cur.fetchall()
        conn.close()
        # 組成 HTML
        text=f'<h2>資料表 {html.escape(table)} 內容</h2>'
        text += '<table border="1" cellspacing="0" cellpadding="6" style="border-collapse: collapse;">'
        # 欄位列
        if colnames:
            text += '<tr>' + ''.join(f'<th>{html.escape(c)}</th>' for c in colnames) + '</tr>'
        else:
            text += '<tr><td colspan="99">(無欄位)</td></tr>'
        # 資料列
        if rows:
            for row in rows:
                text += '<tr>' + ''.join(f'<td>{html.escape(str(v))}</td>' for v in row) + '</tr>'
        else:
            text += '<tr><td colspan="99">(本頁無資料)</td></tr>'
        text += '</table>'
        # 分頁列
        text += f'<p>共 {total_rows} 筆資料,頁 {page}/{total_pages}</p>'
        text += '<div style="margin:10px 0;">'
        if page > 1:
            text += f'<a href="/function/view_table?table={html.escape(table)}&page={page-1}">上一頁</a> '
        if page < total_pages:
            text += f'<a href="/function/view_table?table={html.escape(table)}&page={page+1}">下一頁</a>'
        text += '</div>'
        text += '<a href="/function/list_tables">返回資料表列表</a>'
        return text
    except Exception as e:
        return f'<p>讀取資料時發生錯誤:{html.escape(str(e))}</p>'
    finally:
        if 'conn' in locals():
            conn.close()

此程式使用分頁方式來顯示資料表內的全部紀錄 (預設每頁 50 筆), 首先用 urllib.parse.parse_qs() 函式來解析請求之 URL 字串以取得 table 與 page 參數, 然後用 SELECT COUNT 指令取得紀錄總筆數以便計算要分幾頁來顯示, 結果如下 :




按資料表列表匯出欄的 CSV 超連結會呼叫 /function/export_table 來匯出該資料表內容為 CSV 檔, 程式碼如下 :

# export_table.py
import os
import sqlite3
import csv
from io import StringIO
from flask import Response, request

def main(request, **kwargs):
    # 解析 URL 查詢參數 (?table=xxx)
    table=request.args.get('table')
    if not table:
        return '<p>未指定資料表名稱!<a href="/function/list_tables">返回列表</a></p>'
    DB_PATH='./serverless.db'
    # 檢查資料庫是否存在   
    if not os.path.exists(DB_PATH):
        return '<p>資料庫檔案 serverless.db 不存在!<a href="/function/list_tables">返回列表</a></p>'
    try:
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 取得欄位名稱
        try:
            cur.execute(f'PRAGMA table_info("{table}")')
            columns_info=cur.fetchall()
            if not columns_info:
                return f'<p>資料表 {table} 不存在!<a href="/function/list_tables">返回列表</a></p>'
            columns=[col[1] for col in columns_info]  # col[1] 是欄位名稱
        except Exception as e:
            return f'<p>取得欄位失敗: {str(e)}</p>'
        # 取得所有資料
        try:
            cur.execute(f'SELECT * FROM "{table}"')
            rows=cur.fetchall()
        except Exception as e:
            return f'<p>讀取資料失敗: {str(e)}</p>'
        # 將資料寫入 CSV
        output=StringIO()
        writer=csv.writer(output)
        writer.writerow(columns)
        writer.writerows(rows)
        csv_data=output.getvalue()
        output.close()
        # 回傳 CSV 給瀏覽器下載
        csv_bytes=csv_data.encode('utf-8-sig')        
        return Response(
            csv_bytes,
            mimetype='text/csv',
            headers={'Content-Disposition': f'attachment; filename="{table}.csv"'}
            )   
    except sqlite3.Error as e:
        return f'<p>連線資料庫失敗 {str(e)}</p>'
    finally:
        if 'conn' in locals():
            conn.close()

此程式使用 io.StringIO 類別來將資料表內容轉成 CSV 資料, 注意, 此處為了解決 Excel 在 Windows 版的 BOM 中文亂碼問題, 此 CSV 資料還呼叫了 encode() 來指定 'utf-8-sig' 編碼格式, 最後將編碼後的 CSV 資料利用 flask.Response() 函式傳給瀏覽器下載 : 




開啟 ksml_books.csv 結果如下 :




最後一個模組是用來刪除資料表的 /function/drop_table, 程式碼如下 :

# drop_table.py
import os
import sqlite3
from flask import request, redirect

def main(request, **kwargs):
    # 解析 URL 參數取得資料表名稱
    query=request.query_string.decode('utf-8')
    params=parse_qs(query)
    table=params.get('table', [''])[0]
    DB_PATH='./serverless.db'
    # 檢查資料庫是否存在
    if not os.path.exists(DB_PATH):
        return '''
            <p>資料庫檔案 serverless.db 不存在!
            <a href="/function/list_tables">返回資料表列表</a></p>
            '''
    # 設定保護清單,避免刪除重要系統表
    protected=['call_stats']
    if table in protected:
        return f'''
            <p>資料表 {table} 為保護表,無法刪除!
            <a href="/function/list_tables">返回列表</a></p>
            '''
    try:
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 執行刪除資料表
        cur.execute(f'DROP TABLE IF EXISTS "{table}"')
        conn.commit()
        conn.close()
        # 刪除成功後返回資料表列表
        return f'''
            <p>資料表 {table} 已刪除成功!
            <a href="/function/list_tables">返回列表</a></p>
            '''
    except sqlite3.Error as e:
        return f'<p>刪除資料表 {table} 失敗: {str(e)}</p>'
    finally:
        if 'conn' in locals():
            conn.close()

此程式使用 DROP TABLE 指令來刪除指定資料表, 在資料表列表的刪除欄位中按刪除鈕, 經過確認即可刪除資料表 :






可見 ksml_books 資料表已被刪除. 

OK, 這樣就報完工啦!


2025-10-19 補充 : 

剛剛發現似乎缺了刪除紀錄的功能, 所以我又修改了 view_table.py, 在表格最後添加 "刪除" 欄, 按下超連結菁確認後會呼叫 delete_record.py, 攜帶 table 與 pk (帳號主鍵), 刪除完回 view_table.py :

# view_table.py
import os
import sqlite3
import html
from urllib.parse import parse_qs, quote

def main(request, **kwargs):
    # 解析 URL 查詢參數 (?table=xxx&page=1)
    query=request.query_string.decode('utf-8')
    params=parse_qs(query)
    table=params.get('table', [''])[0]
    try:
        page=int(params.get('page', ['1'])[0])
        if page < 1:
            page=1
    except ValueError:
        page=1    
    DB_PATH='./serverless.db'
    ROWS_PER_PAGE=50  # 每頁顯示筆數
    # 檢查資料庫是否存在
    if not os.path.exists(DB_PATH):
        return '''
        <p>資料庫檔案 serverless.db 不存在!<a href="/function/list_tables">返回資料表列表</a></p>
        '''
    if not table:
        return '''
        <p>缺少 table 參數!<a href="/function/list_tables">返回資料表列表</a></p>
        '''
    try:
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 安全檢查 (避免惡意表名注入)
        cur.execute("""
            SELECT name FROM sqlite_master
            WHERE type='table' AND name=?
        """, (table,))
        if not cur.fetchone():
            conn.close()
            return f'<p>資料表 "{html.escape(table)}" 不存在!</p>'
        # 取得欄位名稱
        cur.execute(f'SELECT * FROM "{table}" LIMIT 1;')
        colnames=[d[0] for d in cur.description] if cur.description else []
        # 計算總筆數
        cur.execute(f'SELECT COUNT(*) FROM "{table}";')
        total_rows=cur.fetchone()[0]
        total_pages=(total_rows + ROWS_PER_PAGE - 1) // ROWS_PER_PAGE
        # 取得當前頁的資料
        offset=(page - 1) * ROWS_PER_PAGE
        cur.execute(f'SELECT * FROM "{table}" LIMIT ? OFFSET ?;', (ROWS_PER_PAGE, offset))
        rows=cur.fetchall()
        conn.close()

        # 組成 HTML
        text=f'<h2>資料表 {html.escape(table)} 內容</h2>'
        text += '<table border="1" cellspacing="0" cellpadding="6" style="border-collapse: collapse;">'
        # 欄位列
        if colnames:
            text += '<tr>'
            text += ''.join(f'<th>{html.escape(c)}</th>' for c in colnames)
            text += '<th>刪除</th>'  # 新增刪除欄位
            text += '</tr>'
        else:
            text += '<tr><td colspan="99">(無欄位)</td></tr>'
        # 資料列
        if rows:
            for row in rows:
                text += '<tr>'
                for v in row:
                    text += f'<td>{html.escape(str(v))}</td>'
                # 假設第一個欄位是主鍵
                pk_value = quote(str(row[0]))
                text += f'<td><a href="/function/delete_record?table={quote(table)}&pk={pk_value}" ' \
                        f'onclick="return confirm(\'確定要刪除此筆紀錄嗎?\')">刪除</a></td>'
                text += '</tr>'
        else:
            text += '<tr><td colspan="99">(本頁無資料)</td></tr>'
        text += '</table>'
        # 分頁列
        text += f'<p>共 {total_rows} 筆資料,頁 {page}/{total_pages}</p>'
        text += '<div style="margin:10px 0;">'
        if page > 1:
            text += f'<a href="/function/view_table?table={quote(table)}&page={page-1}">上一頁</a> '
        if page < total_pages:
            text += f'<a href="/function/view_table?table={quote(table)}&page={page+1}">下一頁</a>'
        text += '</div>'
        text += '<a href="/function/list_tables">返回資料表列表</a>'
        return text
    except Exception as e:
        return f'<p>讀取資料時發生錯誤:{html.escape(str(e))}</p>'
    finally:
        if 'conn' in locals():
            conn.close()





確認刪除會呼叫 delete_record.py :

# delete_record.py
import os
import sqlite3
from flask import redirect, request
from html import escape

def main(request, **kwargs):
    table=request.args.get('table', '').strip()
    pk=request.args.get('pk', '').strip()
    DB_PATH='./serverless.db'
    # 檢查參數
    if not table or not pk:
        return f'<p>缺少 table 或 pk 參數!<a href="/function/list_tables">返回列表</a></p>'
    # 檢查資料庫
    if not os.path.exists(DB_PATH):
        return f'<p>資料庫檔案 serverless.db 不存在!<a href="/function/list_tables">返回列表</a></p>'
    try:  # 刪除紀錄
        conn=sqlite3.connect(DB_PATH)
        cur=conn.cursor()
        # 安全檢查:確認 table 存在
        cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
        if not cur.fetchone():
            return f'<p>資料表 "{escape(table)}" 不存在!<a href="/function/list_tables">返回列表</a></p>'
        # 執行刪除
        cur.execute('DELETE FROM ksml_books WHERE account=?', (pk,))
        conn.commit()
        return redirect(f'/function/view_table?table={table}')
    except sqlite3.Error as e:
        return f'<p>刪除紀錄失敗:{escape(str(e))}</p><a href="/function/view_table?table={escape(table)}">返回</a>'
    finally:
        if 'conn' in locals():
            conn.close()

刪除完返回 view_table.py :




雖然手動刪除使用機會不大, 但系統功能還是要完備. 

最後修改 serverless.py, 將上面 8 個與資料庫管理相關的函式列入被保護的系統模組避免被誤改誤刪 : 

# 需要驗證的函式列表
PROTECTED_FUNCTIONS=['list_functions',
                     'add_function',
                     'save_function',
                     'edit_function',
                     'update_function',
                     'delete_function',
                     'show_stats',
                     'clear_stats',
                     'list_tables',
                     'add_table',
                     'drop_table',
                     'view_table',
                     'show_schema',
                     'export_table',
                     'execute_sql',
                     'delete_record'
                     ]

我把此次 v5 改版 zip 放在 GitHub :


而持續小幅修改的則放在 render.com 部署用的 repo :



2025-10-21 補充 :

今天修改了 view_table.py 中顯示資料表內容的程式碼, 將欄位內容中的 \n 跳行改為 <br> 以便在網頁中呈現跳行效果 : 

        # 資料列
        if rows:
            for row in rows:
                text += '<tr>'
                for v in row:
                    html_nl2br=html.escape(str(v)).replace("\n", "<br>")
                    text += f'<td>{html_nl2br}</td>'

它原本只是 html.escape(str(v)) 而已, 這樣 \n 就沒有跳行效果. 注意, 如果在 f 字串中處理 \n 字元會出錯, 必須先處理完再放進 f 字串裡. 

2025年10月13日 星期一

Mapleboard MP510-50 測試 (四十二) : 安裝 OpenAI 與 Gemini API 套件

今天在 Mapleboard 的 Serverless 平台新增 LINE Bot 後端函式模組 linebot_gpt.py 與 linebot_gemini.py 取得 webhook 網址後, 貼到 LINE Messaging 頁面按 Verify 卻出現錯誤 : 






詢問 ChatGPT 答覆要我檢查 Mapleboard 有無安裝串接這兩個 LLM 的 API, 我用 pip3 show 檢查 openai 與 google-generativeai 才發現一直以來都未曾在 Mapleboard 上安裝套件進行串接 LLM 的測試, 難怪 Verify 失敗 : 

tony1966@LX2438:~/flask_apps/serverless$ pip3 show openai   
WARNING: Package(s) not found: openai
tony1966@LX2438:~/flask_apps/serverless$ pip3 show google-generativeai   
WARNING: Package(s) not found: google-generativeai

安裝這兩個套件後 Verify 就成功了 : 

pip3 install openai

tony1966@LX2438:~/flask_apps/serverless$ pip3 install openai   
Defaulting to user installation because normal site-packages is not writeable
Collecting openai
  Downloading openai-2.3.0-py3-none-any.whl (999 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 999.8/999.8 KB 2.8 MB/s eta 0:00:00
Requirement already satisfied: anyio<5,>=3.5.0 in /home/tony1966/.local/lib/python3.10/site-packages (from openai) (4.9.0)
Requirement already satisfied: pydantic<3,>=1.9.0 in /home/tony1966/.local/lib/python3.10/site-packages (from openai) (2.11.7)
Collecting jiter<1,>=0.10.0
  Downloading jiter-0.11.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (337 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 337.6/337.6 KB 351.7 kB/s eta 0:00:00
Requirement already satisfied: distro<2,>=1.7.0 in /usr/lib/python3/dist-packages (from openai) (1.7.0)
Requirement already satisfied: tqdm>4 in /home/tony1966/.local/lib/python3.10/site-packages (from openai) (4.67.1)
Requirement already satisfied: sniffio in /home/tony1966/.local/lib/python3.10/site-packages (from openai) (1.3.1)
Requirement already satisfied: httpx<1,>=0.23.0 in /home/tony1966/.local/lib/python3.10/site-packages (from openai) (0.28.1)
Requirement already satisfied: typing-extensions<5,>=4.11 in /home/tony1966/.local/lib/python3.10/site-packages (from openai) (4.14.0)
Requirement already satisfied: exceptiongroup>=1.0.2 in /home/tony1966/.local/lib/python3.10/site-packages (from anyio<5,>=3.5.0->openai) (1.2.1)
Requirement already satisfied: idna>=2.8 in /usr/lib/python3/dist-packages (from anyio<5,>=3.5.0->openai) (3.3)
Requirement already satisfied: httpcore==1.* in /home/tony1966/.local/lib/python3.10/site-packages (from httpx<1,>=0.23.0->openai) (1.0.9)
Requirement already satisfied: certifi in /home/tony1966/.local/lib/python3.10/site-packages (from httpx<1,>=0.23.0->openai) (2024.2.2)
Requirement already satisfied: h11>=0.16 in /home/tony1966/.local/lib/python3.10/site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)
Requirement already satisfied: pydantic-core==2.33.2 in /home/tony1966/.local/lib/python3.10/site-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)
Requirement already satisfied: typing-inspection>=0.4.0 in /home/tony1966/.local/lib/python3.10/site-packages (from pydantic<3,>=1.9.0->openai) (0.4.1)
Requirement already satisfied: annotated-types>=0.6.0 in /home/tony1966/.local/lib/python3.10/site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)
Installing collected packages: jiter, openai
Successfully installed jiter-0.11.0 openai-2.3.0


pip3 show google-generativeai

tony1966@LX2438:~/flask_apps/serverless$  pip3 show google-generativeai    
WARNING: Package(s) not found: google-generativeai
tony1966@LX2438:~/flask_apps/serverless$ pip3 install google-generativeai
Defaulting to user installation because normal site-packages is not writeable
Collecting google-generativeai
  Downloading google_generativeai-0.8.5-py3-none-any.whl (155 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 155.4/155.4 KB 728.1 kB/s eta 0:00:00
Requirement already satisfied: tqdm in /home/tony1966/.local/lib/python3.10/site-packages (from google-generativeai) (4.67.1)
Collecting google-ai-generativelanguage==0.6.15
  Downloading google_ai_generativelanguage-0.6.15-py3-none-any.whl (1.3 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.3/1.3 MB 3.8 MB/s eta 0:00:00
Collecting google-auth>=2.15.0
  Downloading google_auth-2.41.1-py2.py3-none-any.whl (221 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 221.3/221.3 KB 4.5 MB/s eta 0:00:00
Requirement already satisfied: typing-extensions in /home/tony1966/.local/lib/python3.10/site-packages (from google-generativeai) (4.14.0)
Collecting google-api-core
  Downloading google_api_core-2.26.0-py3-none-any.whl (162 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 162.5/162.5 KB 5.1 MB/s eta 0:00:00
Requirement already satisfied: protobuf in /home/tony1966/.local/lib/python3.10/site-packages (from google-generativeai) (6.31.1)
Collecting google-api-python-client
  Downloading google_api_python_client-2.184.0-py3-none-any.whl (14.3 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 14.3/14.3 MB 4.7 MB/s eta 0:00:00
Requirement already satisfied: pydantic in /home/tony1966/.local/lib/python3.10/site-packages (from google-generativeai) (2.11.7)
Collecting proto-plus<2.0.0dev,>=1.22.3
  Downloading proto_plus-1.26.1-py3-none-any.whl (50 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 50.2/50.2 KB 3.0 MB/s eta 0:00:00
Collecting protobuf
  Downloading protobuf-5.29.5-cp38-abi3-manylinux2014_aarch64.whl (319 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 319.8/319.8 KB 2.5 MB/s eta 0:00:00
Collecting pyasn1-modules>=0.2.1
  Downloading pyasn1_modules-0.4.2-py3-none-any.whl (181 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 181.3/181.3 KB 5.7 MB/s eta 0:00:00
Collecting rsa<5,>=3.1.4
  Downloading rsa-4.9.1-py3-none-any.whl (34 kB)
Requirement already satisfied: cachetools<7.0,>=2.0.0 in /home/tony1966/.local/lib/python3.10/site-packages (from google-auth>=2.15.0->google-generativeai) (6.1.0)
Requirement already satisfied: requests<3.0.0,>=2.18.0 in /home/tony1966/.local/lib/python3.10/site-packages (from google-api-core->google-generativeai) (2.32.4)
Collecting googleapis-common-protos<2.0.0,>=1.56.2
  Downloading googleapis_common_protos-1.70.0-py3-none-any.whl (294 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 294.5/294.5 KB 5.0 MB/s eta 0:00:00
Requirement already satisfied: httplib2<1.0.0,>=0.19.0 in /usr/lib/python3/dist-packages (from google-api-python-client->google-generativeai) (0.20.2)
Collecting uritemplate<5,>=3.0.1
  Downloading uritemplate-4.2.0-py3-none-any.whl (11 kB)
Collecting google-auth-httplib2<1.0.0,>=0.2.0
  Downloading google_auth_httplib2-0.2.0-py2.py3-none-any.whl (9.3 kB)
Requirement already satisfied: pydantic-core==2.33.2 in /home/tony1966/.local/lib/python3.10/site-packages (from pydantic->google-generativeai) (2.33.2)
Requirement already satisfied: annotated-types>=0.6.0 in /home/tony1966/.local/lib/python3.10/site-packages (from pydantic->google-generativeai) (0.7.0)
Requirement already satisfied: typing-inspection>=0.4.0 in /home/tony1966/.local/lib/python3.10/site-packages (from pydantic->google-generativeai) (0.4.1)
Collecting grpcio<2.0.0,>=1.33.2
  Downloading grpcio-1.75.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl (6.3 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 6.3/6.3 MB 5.4 MB/s eta 0:00:00
Collecting grpcio-status<2.0.0,>=1.33.2
  Downloading grpcio_status-1.75.1-py3-none-any.whl (14 kB)
Requirement already satisfied: pyparsing!=3.0.0,!=3.0.1,!=3.0.2,!=3.0.3,<4,>=2.4.2 in /usr/lib/python3/dist-packages (from httplib2<1.0.0,>=0.19.0->google-api-python-client->google-generativeai) (2.4.7)
Collecting pyasn1<0.7.0,>=0.6.1
  Downloading pyasn1-0.6.1-py3-none-any.whl (83 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 83.1/83.1 KB 2.6 MB/s eta 0:00:00
Requirement already satisfied: urllib3<3,>=1.21.1 in /home/tony1966/.local/lib/python3.10/site-packages (from requests<3.0.0,>=2.18.0->google-api-core->google-generativeai) (2.5.0)
Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests<3.0.0,>=2.18.0->google-api-core->google-generativeai) (3.3)
Requirement already satisfied: charset_normalizer<4,>=2 in /home/tony1966/.local/lib/python3.10/site-packages (from requests<3.0.0,>=2.18.0->google-api-core->google-generativeai) (3.4.2)
Requirement already satisfied: certifi>=2017.4.17 in /home/tony1966/.local/lib/python3.10/site-packages (from requests<3.0.0,>=2.18.0->google-api-core->google-generativeai) (2024.2.2)
Collecting grpcio-status<2.0.0,>=1.33.2
  Downloading grpcio_status-1.75.0-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.74.0-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.73.1-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.73.0-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.72.2-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.72.1-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.71.2-py3-none-any.whl (14 kB)
Installing collected packages: uritemplate, pyasn1, protobuf, grpcio, rsa, pyasn1-modules, proto-plus, googleapis-common-protos, grpcio-status, google-auth, google-auth-httplib2, google-api-core, google-api-python-client, google-ai-generativelanguage, google-generativeai
  Attempting uninstall: protobuf
    Found existing installation: protobuf 6.31.1
    Uninstalling protobuf-6.31.1:
      Successfully uninstalled protobuf-6.31.1
Successfully installed google-ai-generativelanguage-0.6.15 google-api-core-2.26.0 google-api-python-client-2.184.0 google-auth-2.41.1 google-auth-httplib2-0.2.0 google-generativeai-0.8.5 googleapis-common-protos-1.70.0 grpcio-1.75.1 grpcio-status-1.71.2 proto-plus-1.26.1 protobuf-5.29.5 pyasn1-0.6.1 pyasn1-modules-0.4.2 rsa-4.9.1 uritemplate-4.2.0

雖然在 render.com 上成功安裝 serverless 與串接 LLM, 但免費帳戶並不保證服務品質, 還是自己維護的 Mapleboard 靠得住啦!