Argomento

Immagini OG in Python

Questa guida ti mostra come generare immagini OG in Python con FastOG — Django, FastAPI o Flask — firmando un URL HMAC e renderizzando immagini Open Graph dinamiche al volo. Basato su abbonamento con account gratuito (scegli un piano Dynamic API; crea la tua chiave API nella dashboard); usa il Free OG Image Tester per vedere un template prima di integrare.

Guida completa per implementare URL di immagini OG firmati con HMAC in Python.

Avvio rapido

1. Crea il modulo signer

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. Variabili d'ambiente

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

Servizio di firma (Signer Service)

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,
        })

Vista (View)

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,
    })

Template

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>

Tag di template personalizzato (Custom Template Tag)

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})

Esempio di E-commerce

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,
    })

Esempio di Post del Blog

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,
    })

Errori Comuni

Firmare il Messaggio Sbagliato

❌ Errato: f"GET/api/v1/og{canonical}" — manca il separatore di nuova riga. ✅ Corretto: f"GET/api/v1/og\n{canonical}" — metodo + percorso, una nuova riga, poi la query canonica.

Lasciare key Fuori dalla Firma

❌ Errato: firmare solo i tuoi parametri di contenuto e aggiungere key all'URL successivamente. ✅ Corretto: key viene unito ai parametri prima che la query canonica venga costruita e compare nell'URL finale.

Dimenticare di Codificare Chiavi e Valori nell'URL

❌ Errato: costruire la query canonica con valori grezzi e non codificati. ✅ Corretto: codifica in percentuale sia le chiavi che i valori con RFC-3986 (safe='-._~') prima di firmare — usa quote, non quote_plus (che emette + per gli spazi e non corrisponderà al server).

401 missing_signature / invalid_signature

missing_signature (401) significa che key o s manca dall'URL. invalid_signature (401) significa che la query canonica non corrisponde — verifica la nuova riga nel messaggio firmato, lo stesso hmac_secret su entrambi i lati, e quote(safe='-._~') (non quote_plus) per ogni chiave e valore.

Riferimento API Completo

Provalo gratis — nessuna registrazione richiesta

Anteprima e test delle immagini OG dinamiche in pochi secondi.

Apri il tester gratuito di immagini OG

A BeCaSimulations site