在 Python 中生成 OG 圖片
本指南說明如何使用 FastOG 在 Python 中生成 OG 圖片——無論是 Django、FastAPI 或 Flask——透過簽署 HMAC URL 並即時渲染動態 Open Graph 圖片。採用訂閱制,提供免費帳戶(選擇 Dynamic API 方案;在儀表板中建立您的 API 金鑰);在整合前,可使用免費的 OG 圖片測試工具預覽範本。
在 Python 中實作 HMAC 簽署 OG 圖片 URL 的完整指南。
快速開始
1. 建立簽署者模組
python
# utils/fastog.py
import hmac
import hashlib
import os
from urllib.parse import quote, urlencode
def _enc(s):
return quote(str(s), safe='-._~') # RFC-3986: only unreserved chars
def generate_signed_og_url(params: dict, options: dict = None) -> str:
options = options or {}
base_url = options.get('base_url', os.environ.get('FASTOG_BASE_URL', 'https://fastog.com/api/v1/og'))
api_key = options.get('api_key', os.environ.get('FASTOG_API_KEY'))
hmac_secret = options.get('hmac_secret', os.environ.get('FASTOG_HMAC_SECRET'))
if not api_key or not hmac_secret:
raise ValueError("Missing FASTOG_API_KEY or FASTOG_HMAC_SECRET")
all_params = {**params, 'key': api_key}
pairs = []
for k, v in all_params.items():
for vv in sorted(v if isinstance(v, list) else [v]):
pairs.append(f"{_enc(k)}={_enc(vv)}")
canonical = '&'.join(sorted(pairs))
signature = hmac.new(
hmac_secret.encode(),
f"GET/api/v1/og\n{canonical}".encode(),
hashlib.sha256
).hexdigest()
return f"{base_url}?{urlencode({**all_params, 's': signature})}"
2. 環境變數
bash
# .env
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here
bash
pip install python-dotenv
python
# config.py
from dotenv import load_dotenv
load_dotenv()
Django
Signer 服務
python
# services/fastog.py
from utils.fastog import generate_signed_og_url
class QuickogService:
@staticmethod
def get_og_url(template: str, **params) -> str:
return generate_signed_og_url({
'template': template,
**params,
})
視圖
python
# views.py
from django.shortcuts import render
from services.fastog import QuickogService
def blog_post(request, slug):
post = get_post(slug)
og_image_url = QuickogService.get_og_url(
template='blog',
title=post.title,
subtitle=post.excerpt,
author=post.author.name,
)
return render(request, 'blog/post.html', {
'post': post,
'og_image_url': og_image_url,
})
模板
django
{# templates/blog/post.html #}
<!DOCTYPE html>
<html>
<head>
<meta property="og:image" content="{{ og_image_url }}" />
<meta property="og:title" content="{{ post.title }}" />
<meta property="og:description" content="{{ post.excerpt }}" />
</head>
<body>
<h1>{{ post.title }}</h1>
<p>{{ post.excerpt }}</p>
</body>
</html>
自訂模板標籤
python
# templatetags/fastog_tags.py
from django import template
from services.fastog import QuickogService
register = template.Library()
@register.simple_tag
def og_image_url(template_name, **params):
return QuickogService.get_og_url(template_name, **params)
django
{# In template #}
{% load fastog_tags %}
<meta property="og:image" content="{% og_image_url 'blog' title=post.title subtitle=post.excerpt %}" />
FastAPI
python
# main.py
from fastapi import FastAPI, Query
from pydantic import BaseModel
from utils.fastog import generate_signed_og_url
app = FastAPI()
class OgRequest(BaseModel):
title: str
template: str = "default"
subtitle: str | None = None
@app.get("/api/og")
def generate_og(title: str = Query(...), template: str = Query("default")):
og_url = generate_signed_og_url({
'template': template,
'title': title,
})
return {"ogImageUrl": og_url}
@app.get("/blog/{slug}")
async def blog_post(slug: str):
post = await get_post(slug)
og_url = generate_signed_og_url({
'template': 'blog',
'title': post.title,
'subtitle': post.excerpt,
})
return {"post": post, "ogImageUrl": og_url}
Flask
python
# app.py
from flask import Flask, render_template, request, jsonify
from utils.fastog import generate_signed_og_url
app = Flask(__name__)
@app.route("/blog/<slug>")
def blog_post(slug):
post = get_post(slug)
og_image_url = generate_signed_og_url({
'template': 'blog',
'title': post['title'],
'subtitle': post['excerpt'],
})
return render_template('blog/post.html', post=post, og_image_url=og_image_url)
@app.route("/api/og")
def api_og():
title = request.args.get('title')
template = request.args.get('template', 'default')
if not title:
return jsonify({'error': 'Missing title'}), 400
og_url = generate_signed_og_url({
'template': template,
'title': title,
})
return jsonify({'ogImageUrl': og_url})
電子商務範例
python
# views.py
def product_detail(request, product_id):
product = get_product(product_id)
og_image_url = generate_signed_og_url({
'template': 'ecommerce',
'title': product.name,
'price': product.formatted_price,
'image': product.image_url,
})
return render(request, 'products/detail.html', {
'product': product,
'og_image_url': og_image_url,
})
部落格文章範例
python
def user_profile(request, username):
user = get_user(username)
og_image_url = generate_signed_og_url({
'template': 'blog',
'title': user.name,
'subtitle': user.bio,
'author': user.name,
})
return render(request, 'profile/show.html', {
'user': user,
'og_image_url': og_image_url,
})
常見陷阱
簽署錯誤的訊息
❌ 錯誤:f"GET/api/v1/og{canonical}" — 缺少換行分隔符號。
✅ 正確:f"GET/api/v1/og\n{canonical}" — 方法 + 路徑、一個換行,然後是正規化查詢字串。
將 key 遺漏在簽章之外
❌ 錯誤:只簽署你的內容參數,之後才將 key 附加到 URL 上。
✅ 正確:key 會在建立正規化查詢字串之前合併進參數中,並出現在最終的 URL 裡。
忘記對鍵與值進行 URL 編碼
❌ 錯誤:使用未編碼的原始值來建立正規化查詢字串。
✅ 正確:在簽署前,使用 RFC-3986(safe='-._~')對鍵與值進行百分號編碼 — 請使用 quote,而非 quote_plus(後者會將空格輸出為 +,且無法與伺服器比對相符)。
401 missing_signature / invalid_signature
missing_signature(401)表示 URL 中缺少 key 或 s。invalid_signature(401)表示正規化內容不符 — 請確認簽署訊息中的換行、兩端使用相同的 hmac_secret,以及每個鍵與值都使用 quote(safe='-._~')(而非 quote_plus)。