Python 3.14 的 t-string:和 f-string 差在哪,怎麼用來防 SQL 注入

f-string 立刻組成字串,使用者輸入就混進 SQL 裡。t-string 把文字和插值分開交給你處理,可以安全地轉成參數化查詢或跳脫 HTML。附實測與兩個容易踩的坑。

f"... WHERE name = '{name}'" 很方便,也是 SQL 注入的經典寫法。Python 3.14 新增的 t-string 寫法幾乎一樣,但結果不是字串,而是一個能看見「哪些是程式寫的文字、哪些是外部的值」的物件。

f-string 和 t-string 的差別

from string.templatelib import Template, Interpolation

name = "Danny"
f = f"Hello {name}"
t = t"Hello {name}"

print(type(f), repr(f))
print(type(t))
print(t.strings)
print(t.values)
for part in t:
    print(repr(part))

Python 3.14.4 的輸出:

 'Hello Danny'

('Hello ', '')
('Danny',)
'Hello '
Interpolation('Danny', 'name', None, '')

f-string 立刻組成字串,Danny 從哪裡來的資訊就消失了。t-string 得到 Template 物件,逐一走訪時,文字是 str,插值是 Interpolation,裡面有值、原始運算式、轉換符號和格式設定。

要怎麼組合,由接收它的函式決定。

用 t-string 產生參數化查詢

def sql(template: Template) -> tuple[str, list]:
    """字串部分照抄,插值部分換成 ? 並收集參數。"""
    if not isinstance(template, Template):
        raise TypeError("sql() 只接受 t-string,請用 t\"...\"")
    query, params = [], []
    for part in template:
        if isinstance(part, Interpolation):
            query.append("?")
            params.append(part.value)
        else:
            query.append(part)
    return "".join(query), params

用 sqlite3 建三個使用者,模擬攻擊者輸入 nobody' OR '1'='1:

name = "nobody' OR '1'='1"

q = f"SELECT id, name FROM users WHERE name = '{name}'"
print("f-string:", q)
print("  結果:", db.execute(q).fetchall())

q, params = sql(t"SELECT id, name FROM users WHERE name = {name}")
print("t-string:", q, params)
print("  結果:", db.execute(q, params).fetchall())
f-string: SELECT id, name FROM users WHERE name = 'nobody' OR '1'='1'
  結果: [(1, 'alice'), (2, 'bob'), (3, 'root')]
t-string: SELECT id, name FROM users WHERE name = ? ["nobody' OR '1'='1"]
  結果: []

f-string 版本撈出全部使用者,包含管理員 root。t-string 版本把輸入當成一個普通的值,查無資料。正常查詢不受影響:

正常查詢: [(2, 'bob')]

sql() 檢查型別,不小心寫成 f-string 時會直接報錯:

TypeError: sql() 只接受 t-string,請用 t"..."

f-string 已經是組好的字串,函式沒辦法分辨哪段是使用者輸入,只能拒絕。

用 t-string 跳脫 HTML

同樣的做法,只跳脫插值的部分:

from html import escape

def html(template: Template) -> str:
    out = []
    for part in template:
        if isinstance(part, Interpolation):
            out.append(escape(str(part.value)))
        else:
            out.append(part)
    return "".join(out)

comment = 'alert("xss")'
print(f"<p>{comment}</p>")
print(html(t"<p>{comment}</p>"))
<p>alert("xss")</p>
<p>&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;</p>

程式寫的 <p> 保留,使用者輸入的 `` 被跳脫。

格式設定會保留下來

price = 1234.5
t = t"價格 {price:,.2f} 元 {price!r}"
for part in t:
    print(repr(part))
'價格 '
Interpolation(1234.5, 'price', None, ',.2f')
' 元 '
Interpolation(1234.5, 'price', 'r', '')

:,.2f 和 !r 不會自動套用,存在 format_spec、conversion 欄位裡,由處理函式決定要不要用。上面的 sql()、html() 都沒處理它們,實際使用時要記得。

陷阱一:str() 不會組成字串

print(str(t"x {1}"))
Template(strings=('x ', ''), interpolations=(Interpolation(1, '1', None, ''),))

Template 沒有預設的組合方式,str() 只會得到物件的描述。一定要交給處理函式。

陷阱二:範例檔不要叫 html.py

寫這篇的範例時,第一個 HTML 範例的檔名是 html.py,執行就出錯:

ImportError: cannot import name 'escape' from 'html' (consider renaming '.../html.py' since it has the same name as the standard library module named 'html' and prevents importing that standard library module)

自己的檔案蓋掉了標準函式庫的 html 模組。Python 3.14 的錯誤訊息會直接建議改檔名,改成 html_escape.py 就好。email.py、json.py、random.py 也是常見的例子。

現在可以用了嗎

t-string 需要 Python 3.14 以上。

PostgreSQL 的 psycopg 從 3.3 版(2025-12-01 發布)開始支援 t-string,可以直接 cursor.execute(t"... WHERE name = {name}"),由 psycopg 負責轉成安全的參數。標準函式庫的 sqlite3 目前仍然只接收字串和參數,要自己寫上面那種 sql() 轉換函式。

自己寫的 API 也可以照這個思路:只接受 Template,從介面上避免有人把使用者輸入直接組進 SQL 或 HTML。

關於作者

已發表 274 篇文章

留言

還沒有留言。有補充、疑問或不同做法,歡迎第一個留言。

發表留言

Email 不會公開,只用於回覆通知。

第一次留言需經審核,之後會直接顯示。