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

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 靠得住啦! 

2025年10月10日 星期五

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

今天在測試如何將 Mapleboard 上的仿 GCF 之 serverless app 移植到 Render 上時, 發現主程式 serverless.py 有不完美之處 : 我居然沒有設定根目錄路徑! 為此進行了小改版, 版本提升為 v4. 

本系列全部測試文章參考 :


其實只是在 serverless.py 添加下列根目錄存取的回應程式碼而已 :

# 根目錄
@app.route("/")
def index():
    return '<p>Serverless API 運行中! <a href="/login">登入系統</a></p>'

因為修改了主程式, 所以必須重啟服務才會生效 :

tony1966@LX2438:~/flask_apps/serverless$ sudo systemctl restart serverless    
[sudo] tony1966 的密碼: 

檢視服務狀態 : 

tony1966@LX2438:~/flask_apps/serverless$ sudo systemctl status serverless   
● serverless.service - Serverless Flask App
     Loaded: loaded (/etc/systemd/system/serverless.service; enabled; vendor pr>
     Active: active (running) since Fri 2025-10-10 18:05:15 CST; 21s ago
   Main PID: 88782 (gunicorn: maste)
      Tasks: 5 (limit: 4213)
     Memory: 68.0M
        CPU: 3.294s
     CGroup: /system.slice/serverless.service
             ├─88782 "gunicorn: master [serverless:app]" "" "" "" "" "" "" "" ">
             ├─88784 "gunicorn: worker [serverless:app]" "" "" "" "" "" "" "" ">
             ├─88785 "gunicorn: worker [serverless:app]" "" "" "" "" "" "" "" ">
             ├─88786 "gunicorn: worker [serverless:app]" "" "" "" "" "" "" "" ">
             └─88787 "gunicorn: worker [serverless:app]" "" "" "" "" "" "" "" ">

Oct 10 18:05:15 LX2438 systemd[1]: Started Serverless Flask App.
Oct 10 18:05:15 LX2438 gunicorn[88782]: [2025-10-10 18:05:15 +0800] [88782] [IN>
Oct 10 18:05:15 LX2438 gunicorn[88782]: [2025-10-10 18:05:15 +0800] [88782] [IN>
Oct 10 18:05:15 LX2438 gunicorn[88782]: [2025-10-10 18:05:15 +0800] [88782] [IN>
Oct 10 18:05:15 LX2438 gunicorn[88784]: [2025-10-10 18:05:15 +0800] [88784] [IN>
Oct 10 18:05:15 LX2438 gunicorn[88785]: [2025-10-10 18:05:15 +0800] [88785] [IN>
Oct 10 18:05:15 LX2438 gunicorn[88786]: [2025-10-10 18:05:15 +0800] [88786] [IN>
Oct 10 18:05:15 LX2438 gunicorn[88787]: [2025-10-10 18:05:15 +0800] [88787] [IN>
lines 1-22/22 (END)

拜訪 Mapleboard 的 Flask app 子網域根目錄 :





按 "登入系統" 輸入密碼 :




登入成功就可以線上管理函式模組了 :




我把 serverless_v4.zip 放在 GitHub :



2025-10-17 補充 : 

今天修改根目錄的處理方式, 上面的作法較簡單, 只是固定顯示登入連結, 即使已登入狀態存取根目錄也是如此, 這種情況應該顯示函式列表較合理, 修改如下 : 

# 根目錄
@app.route("/")
def index():
    if check_auth(): # 若已登入導向函式列表頁面        
        return redirect('/function/list_functions')
    else:  # 否則顯示登入提示        
        return '<p>Serverless API 運行中! <a href="/login">登入系統</a></p>' 

首先會呼叫 check_auth() 看看是否為已登入狀態, 是的話就呼叫 flask.redirect() 重導至函式列表模組 list_functions, 否則就顯示登入頁面, 程式前面須匯入 redirect() 函式. 

注意, 此處 redirect() 必須直接傳入函式模組之路徑, 如果使用 url_for('list_functions') 會出現錯誤,  因為 serverless.py  是動態載入要執行的函式模組, 而 url_for() 是透過 Flask 內部的 endpoint 映射表 (app.url_map) 來尋找對應函式的, 動態載入情況下, Flask 無法在啟動階段 (app 建立時) 就知道有這個函式的  endpoint. 

2025年8月28日 星期四

Mapleboard MP510-50 測試 (四十) : 加強 Fail2ban 的 sshd 封鎖條件

自從安裝 Fail2Ban 後, 持續收到它寄來的 IP 封鎖報告郵件, 企圖暴力破解 ssh 密碼的駭客行為一天至少 10 次以上 :




目前的封鎖設定如下 :

tony1966@LX2438:~$ sudo cat /etc/fail2ban/jail.local
[sudo] tony1966 的密碼: 
...
(略)
...
[sshd]
enabled = true
port = 22
logpath = /var/log/auth.log
maxretry = 5
bantime = 1h
findtime = 10m
action = %(action_mw)s

此設定為十分鐘內超過 5 次錯誤就封鎖一個小時, 我決定加強封鎖條件, 修改如下 :

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




新設定是 15 分鐘內超過 3 次錯誤就封鎖 12 個小時, 改完須重啟服務才會生效 :

tony1966@LX2438:~$ sudo systemctl restart fail2ban  

檢視目前的封鎖項目 : 

tony1966@LX2438:~$ sudo fail2ban-client status   
Status
|- Number of jail: 5
`- Jail list: nginx-404, nginx-badbots, nginx-noscript, recidive, sshd

檢視目前 sshd 封鎖狀態 :

tony1966@LX2438:~$ sudo fail2ban-client status sshd  
[sudo] tony1966 的密碼: 
Status for the jail: sshd
|- Filter
|  |- Currently failed: 7
|  |- Total failed: 16
|  `- File list: /var/log/auth.log
`- Actions
   |- Currently banned: 4
   |- Total banned: 4
   `- Banned IP list: 213.6.203.226 5.29.135.63 103.189.235.60 189.47.10.153 

透過減少嘗試次數可降低暴力破解成功機率, 用 12 小時長時間封鎖來拖垮機器人駭客.


2025-09-01 補充 :

因為 Fail2Ban 封鎖條件變嚴格後, Gmail 收到封鎖通知信的頻率變高, 收件夾都被淹沒了. 問 ChatGPT 解決方案, 原來可以用 Buffered 的方式, 指定 12/24 小時才整批寄出一封通知信, 作法很簡單, 就是把 jail.local 裡 [sshd] 的 action 從 %(action_mw)s 改成 %(action_mwlb)s :

用 nano 編輯 jail.local 設定檔 :

tony1966@LX2438:~$ sudo nano /etc/fail2ban/jail.local   
[sudo] tony1966 的密碼: 




這樣會將多次封鎖事件暫存起來, 定期批次寄一封信, 信件內容會包含多個被封鎖的 IP.  預設批次寄信的間隔約 1 小時, 可以在 [DEFAULT] 中指定 :

[DEFAULT]
mta = sendmail
destemail = 我的 Gmail 
sender = 我的 Gmail
banaction = iptables-multiport
action = %(action_mwlb)s[name=SSH, buffer=43200]

此處 buffer 參數用來指定美批次送信間隔秒數  :

buffer=86400 : 每 24 小時寄一次彙整通知
buffer=43200 : 每 12 小時寄一次

按 Ctro+O 存檔再按 Ctrl+X 跳出 nano. 

但重啟卻出現錯誤 :

tony1966@LX2438:~$ sudo fail2ban-client reload  
[sudo] tony1966 的密碼: 
2025-09-01 16:36:45,085 fail2ban                [399327]: ERROR   Failed during configuration: Bad value substitution: option 'action' in section 'sshd' contains an interpolation key 'action_mwlb' which is not a valid option name. Raw value: '%(action_mwlb)s'

原因是 action_mwlb 並不存在, 「b」(buffer) 的版本在某些發行版或新版 Fail2Ban 才有, 不是通用的. 只好恢復原狀. 

2025年8月11日 星期一

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

在前一篇完成重構的 serverless 平台 v2 版中, 我將所有應用會用到的金鑰與全權杖等集中於系統目錄下的環境變數檔 .env 統一管理; 本篇則是要在此基礎上為此 serverless 函式執行平台添加呼叫統計功能, 為此也修改了主程式動態載入函式模組時傳遞給 main() 函式的參數結構, 添加了一個 protected 參數來傳送管理模組名稱串列給函式模組. 

本系列全部測試文章參考 :

呼叫紀錄儲存在平台根目錄 ~/flask_apps/serverless 下的一個名為 serverless.db 的 SQLite 資料庫檔案, 其用法參考 : 


本篇只會在 severless.db 中建立並維護一個兩欄位 (func_name 與 call_count) 的資料表 call_stats, 用來記錄被呼叫的函式模組名稱與累加的被呼叫次數. 取名為 serverless.db 是為了保留未來功能擴充性. 


1. 修改主程式 serverless.py :

主要是增加 sqlite3 模組之匯入, 第一次執行時的資料庫初始化函式, 以及每次函式模組被呼叫前的統計增量函式 :

# serverless.py
from flask import Flask, request, jsonify, session  
import importlib.util
import os
import logging
from dotenv import dotenv_values
import sqlite3

# 指定呼叫統計資料庫位置 (必須在 init_db() 定義之前)
DB_PATH='./serverless.db'

def check_auth():  # 檢查使用者是否已登入
    return session.get('authenticated') == True

def init_db():  # 初始化呼叫紀錄資料庫
    if not os.path.exists(DB_PATH):
        conn=sqlite3.connect(DB_PATH)
        cursor=conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS call_stats (
                func_name TEXT PRIMARY KEY,
                call_count INTEGER NOT NULL
                )
            """)
        conn.commit()
        conn.close()

def record_call(func_name):  # 紀錄函式呼叫次數
    if not os.path.exists(DB_PATH):  # 若資料庫檔不存在就建立
        init_db()   
    try:
        conn=sqlite3.connect(DB_PATH)
        cursor=conn.cursor()
        cursor.execute('SELECT call_count FROM call_stats WHERE func_name=?', (func_name,))
        row=cursor.fetchone()
        if row:  # 有找到 : 呼叫次數增量 1
            cursor.execute('UPDATE call_stats SET call_count=call_count + 1 WHERE func_name=?', (func_name,))
        else:  # 沒找到 : 第一次呼叫設為 1
            cursor.execute('INSERT INTO call_stats (func_name, call_count) VALUES (?, 1)', (func_name,))
        conn.commit()
        conn.close()
    except Exception as e:
        logging.error(f'Failed to record call stats for {func_name}: {e}')

app=Flask(__name__)
# 初始化資料庫
init_db()  
# 從 .env 讀取權杖 (密碼) 與金鑰
config=dotenv_values('.env')
SECRET_TOKEN=config.get('SECRET_TOKEN')  # 易記的令牌 (類似密碼)
SECRET_KEY=config.get('SECRET_KEY')  # 簽章加密用的金鑰
app.secret_key=SECRET_KEY  # 用來簽章與驗證 session cookie
# 指定函式模組所在的資料夾
FUNCTIONS_DIR=os.path.expanduser('./functions')
# 指定錯誤日誌檔 (在目前工作目錄下)
logging.basicConfig(filename='serverless_error.log', level=logging.ERROR)
# 需要驗證的函式列表
PROTECTED_FUNCTIONS=['list_functions',
                     'add_function',
                     'save_function',
                     'edit_function',
                     'update_function',
                     'delete_function',
                     'show_stats',
                     'clear_stats'
                     ]
# 登入管理功能
@app.route('/login', methods=['GET', 'POST'])
def login():
    # GET 請求 : 顯示登入頁面
    if request.method == 'GET':  
        return '''
        <!DOCTYPE html>
        <html>
        <head><title>系統登入</title></head>
        <body>
            <h2>系統登入</h2>
            <form method="post">
                <input type="password" name="token" placeholder="請輸入密碼" required>
                <button type="submit">登入</button>
            </form>
        </body>
        </html>
        '''
    # POST 請求 : 處理登入請求
    if request.is_json:  # JSON 登入 
        token=request.json.get('token')
    else:   # 表單登入
        token=request.form.get('token')    
    if token == SECRET_TOKEN:  # 驗證登入密碼
        # 將登入狀態儲存在瀏覽器的 session cookie 中 (以明碼方式儲存)
        # Flask 會用金鑰對資料進行簽章 (非加密) 確保內容未被竄改
        session['authenticated']=True    
        # 回應登入成功
        if request.is_json:  
            return jsonify({'message': '登入成功'})
        else:
            return '<p>登入成功!<a href="/function/list_functions">查看函式列表</a></p>'
    else:  # 密碼錯誤 : 回應登入失敗訊息
        if request.is_json:
            return jsonify({'message': '登入失敗'}), 401
        else:
            return '<p>登入失敗!<a href="/login">重新登入</a></p>', 401

# 登出管理功能 
@app.route('/logout')
def logout():
    session.clear()  # 清除伺服端 Flask session 字典中的所有鍵值對
    return '<p>已登出!<a href="/login">重新登入</a></p>'

# 動態載入 & 執行函式模組 (支援 RESTful) 
@app.route('/function/<func_name>', defaults={'subpath': ''}, methods=['GET', 'POST'])
@app.route('/function/<func_name>/<path:subpath>', methods=['GET', 'POST'])
def handle_function(func_name, subpath):  # 傳入 subpath 支援 RESTful
    # 1. 如果呼叫管理模組必須使用者已登入才行
    if func_name in PROTECTED_FUNCTIONS and not check_auth():
        return jsonify({'error': 'Authentication required', 'login_url': '/login'}), 401    
    # 2. 取得檔案路徑
    func_path=os.path.join(FUNCTIONS_DIR, f'{func_name}.py')
    if not os.path.isfile(func_path):  # 模組檔案不存在 -> 回 404
        return jsonify({'error': f'Function "{func_name}" not found'}), 404
    try:
        # 3. 動態載入模組 (絕對路徑)
        spec=importlib.util.spec_from_file_location(func_name, func_path)
        module=importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        # 4. 檢查模組中有無 main() 函式 :
        if not hasattr(module, 'main'):  # 模組中無 main() 函式
            return jsonify({'error': f'Module "{func_name}" has no main()'}), 400
        # 5. 將 subpath 加入 request 中 (支援 RESTful)
        request.view_args['subpath']=subpath
        # 6. 記錄呼叫統計 (除了統計查詢自身避免無限循環)
        if func_name not in PROTECTED_FUNCTIONS:
            record_call(func_name)        
        # 7. 執行模組中的函式 (傳入模組可能需要的參數-但不一定會用到) :        
        result=module.main(request, config=config, protected=PROTECTED_FUNCTIONS)
        # 8. 傳回函式執行結果
        return result 
    except Exception as e:
        logging.exception(f'Error in function {func_name}\n{e}')  # 紀錄錯誤於日誌
        return jsonify({'error': 'Function execution failed'}), 500

if __name__ == '__main__':
    init_db()  # 初始化資料庫
    app.run(debug=True)

其中黃底色部分為呼叫紀錄功能所增加的程式碼, 主要就是新增 show_stats.py 與 clear_stats.py 這兩個函式模組, 它們也是列在被保護的模組, 不會顯示在 list_functions.py 呈現的模組列表 (無法限上編輯與刪除). 其次是新增了 init_db() 與 record_call() 這兩個函式, 當主程式執行時會先呼叫 init_db() 初始化 SQLite 資料庫 serverless.db, 建立一個 call_stats 資料表來紀錄函式模組名稱與被呼叫次數, 除了被保護模組外的其他模組每次被動態載入前都會先呼叫 record_call() 函式讓其呼叫次數增量 1. 注意, 主程式只記錄非管理模組被呼叫之累加次數. 

另外, 本次改版也修改了動態載入模組時呼叫 module.main() 的傳入參數結構, 多了一個 protected 參數把管理模組名稱串列 PROTECTED_FUNCTIONS 傳給被載入之模組, 因為在 list_functions.py 與 show_stats.py 中列表中不需要顯示管理模組, 這時就需要用 protected 參數來判斷. 在函式模組中從 **kwargs 取出 protected 的語法如下 :

def main(request, **kwargs):
    # 取得主程式傳遞之 protected 參數 (被保護之管理模組名稱)
    protected=kwargs.get('protected', []) 

這個 **kwargs 參數包含全部主程式所傳遞的參數字典, 不是每個函式模組都會用到, 會用到的就呼叫 kwargs.get() 自行取用. 


2. 建立顯示呼叫統計的函式模組 show_stats.py :

此新增模組用來顯示各模組 (被保護模組除外) 的呼叫次數統計, 主要動作是連線 SQLite 資料庫 serverless.db 讀取其中的 call_stats 資料表, 然後用迴圈產生模組被呼叫次數表格之 HTML 字串後傳回 : 

# show_stats.py
import sqlite3

DB_PATH='./serverless.db'

def main(request, **kwargs):
    # 取得主程式傳遞之 protected 參數 (被保護之管理模組名稱)
    protected=kwargs.get('protected', [])    
    # 連線資料庫
    conn=sqlite3.connect(DB_PATH)
    cursor=conn.cursor()
    cursor.execute('SELECT func_name, call_count FROM call_stats ORDER BY func_name')
    rows=cursor.fetchall()
    conn.close()
    # 產生回應表格
    html='<h2>函式呼叫統計</h2>'
    html += '<table border="1" cellpadding="6" cellspacing="0" style="border-collapse: collapse;">'
    html += '<tr><th>函式名稱</th><th>呼叫次數</th></tr>'
    for func_name, count in rows:
        if func_name in protected:  # 不顯示管理模組之被呼叫次數
            continue
        html += f'<tr><td>{func_name}</td><td>{count}</td></tr>'
    html += '</table>'
    html += '<br><a href="/function/clear_stats">清除統計資料</a> '
    html += '<a href="/function/list_functions">返回函式列表</a>'
    return html

雖然此模組是被動態載入到主程式 serverless.py 中執行, 主程式已經匯入 sqlite 模組也有定義 DB_PATH, 但 show_stats 本身是獨立的模組, 在執行其 main() 函式時, 裡面用到的外部資源 (像是 sqlite3 與資料庫路徑 DB_PATH) 都需要自己在這個模組內 import 並設定之, 因為它們是互不影響的不同模組空間. 

其次, 此模組不顯示管理模組之輩呼叫次數, 故先用 kwargs.get() 取出主程式傳遞的 protected 參數以便在迴圈中用 continue 跳過它們. 


3. 建立清除呼叫統計的函式模組 clear_stats.py :

此函式模組用來刪除 serverless.d 資料庫中的 call_stats 資料表中的全部紀錄, 重新統計函式呼叫次數 : 

# clear_stats.py
import sqlite3
from flask import jsonify, session

DB_PATH='./serverless.db'

def main(request, **kwargs):
    # 權限檢查確保只有登入用戶能清除呼叫統計
    if not session.get('authenticated'):
        return jsonify({'error': 'Authentication required'}), 401
    # 清除 call_stats 資料表
    try:
        conn=sqlite3.connect(DB_PATH)
        cursor=conn.cursor()
        cursor.execute('DELETE FROM call_stats')
        conn.commit()
        conn.close()
        return f'''
        <p>已成功清除呼叫統計資料.</p>
        <a href="/function/show_stats">返回呼叫統計列表</a>
        '''
    except Exception as e:
        return jsonify({'error': f'清除呼叫統計失敗: {e}'}), 500

為了保險起見, 函式開頭會先驗證是否為已登入狀態, 成功清除後會顯示回呼叫統計列表的連結. 


4. 修改顯示函式模組列表程式 list_functions.py :

模組 list_functions.py 作為本平台管理頁面的儀錶板, 所以我在函式模組列表上方添加一個 "呼叫統計" 超連結, 其餘內容不變 : 

# list_functions.py
import os

def main(request, **kwargs):
    # 取得主程式傳遞之 protected 參數 (被保護之管理模組名稱)
    proteted=kwargs.get('protected', [])     
    # 取得 functions 目錄絕對路徑
    functions_dir='./functions'
    # 取得所有 .py 檔案(但排除 __init__.py)
    try:
        files=os.listdir(functions_dir)
        py_files=[f[:-3] for f in files if f.endswith('.py') and f != '__init__.py']
        py_files.sort()  # 按字母順序排序
    except FileNotFoundError:
        return '<p>directory ./functions not found!</p>'
    # 產生 HTML 碼
    html = '<h2>函式列表</h2>'
    html += '<table border="1" cellspacing="0" cellpadding="6" style="border-collapse: collapse;">'
    html += '<tr><th>函式名稱</th><th>執行</th><th>編輯</th><th>刪除</th></tr>'
    for func in py_files:
        if func in protected:  # 不顯示管理模組
            continue
        html += f'<tr>'
        html += f'<td>{func}</td>'
        html += f'<td><a href="/function/{func}">執行</a></td>'
        html += f'<td><a href="/function/edit_function?module_name={func}">編輯</a></td>'
        html += f'<td><a href="/function/delete_function?module_name={func}">刪除</a></td>'
        html += f'</tr>'
    html += '</table>'
    html += '<br><a href="/function/add_function">新增函式</a> '
    html += '<a href="/function/show_stats">呼叫統計</a> '    
    html += '<a href="/logout">登出</a>'
    return html

此模組主要修改之處為黃底高亮部分, 增加了從 protected 參數中取得主程式傳遞的 PROTECT_FUNCTIONS 串列, 供迴圈中判斷是否為管理模組, 是的話就不顯示, 這樣就只要在主程式中維護一份 PROTECT_FUNCTIONS 串列即可; 其次是在底下增加一個呼叫 show_stats 模組的超連結前往顯示呼叫統計次數頁面. 

由於更改了 serverless.py, 所以需重啟 serverless.service (手動刪除 serverless.db 則不需要重啟服務):

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

瀏覽 list_functions 頁面 :




點各模組的 "執行" 超連結各一次後, 按 "呼叫統計" 超連結會顯示呼叫次數統計 :



 
按 "清除統計" 連結會清空呼叫次數統計資料表 call_stats :



按 "返回呼叫統計列表" 連結顯示為空 :




從呼叫統計即可明瞭各函式模組被呼叫之次數, 例如 LINE Bot 程式回應了多少次. 我將此新版 v3 的壓縮檔存放於 GitHub :