如何使用 Python 的加密包签署 AMP 更新缓存请求?
How do I sign an AMP update-cache request with Python's cryptography package?
如何使用 Python 的加密包为 AMP 的 update-cache API 签署 URL?
这是核心签名逻辑,它将确定更新缓存请求的路径和查询参数。此处,域是您网站的实际域,而不是特殊的 AMP 子域。
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
def sign_amp_update_cache_url(private_key: bytes, domain: str, url: str) -> str:
private_key = serialization.load_pem_private_key(private_key, password=None) # or whatever your key's password is
message = f"/update-cache/c/s/{domain}{url}?amp_action=flush&_ts={int(time.time())}"
binary_signature = private_key.sign(
message.encode("UTF-8"),
padding.PKCS1v15(),
hashes.SHA256()
)
encoded_signature = base64.b64encode(binary_signature, altchars=b"-_").replace(b"=", b"").decode("UTF-8")
signed_url = f"{message}&_url_signature={encoded_signature}"
return signed_url
要完成请求的准备工作,您必须compute the AMP cache subdomain for your domain, get the updateCacheApiDomainSuffix from caches.json, and concatenate the AMP cache subdomain, updateCacheApiDomainSuffix, and signed AMP update cache URL from the function above. Here are Google's docs on the process with examples of what the cache URL should look like.
如何使用 Python 的加密包为 AMP 的 update-cache API 签署 URL?
这是核心签名逻辑,它将确定更新缓存请求的路径和查询参数。此处,域是您网站的实际域,而不是特殊的 AMP 子域。
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
def sign_amp_update_cache_url(private_key: bytes, domain: str, url: str) -> str:
private_key = serialization.load_pem_private_key(private_key, password=None) # or whatever your key's password is
message = f"/update-cache/c/s/{domain}{url}?amp_action=flush&_ts={int(time.time())}"
binary_signature = private_key.sign(
message.encode("UTF-8"),
padding.PKCS1v15(),
hashes.SHA256()
)
encoded_signature = base64.b64encode(binary_signature, altchars=b"-_").replace(b"=", b"").decode("UTF-8")
signed_url = f"{message}&_url_signature={encoded_signature}"
return signed_url
要完成请求的准备工作,您必须compute the AMP cache subdomain for your domain, get the updateCacheApiDomainSuffix from caches.json, and concatenate the AMP cache subdomain, updateCacheApiDomainSuffix, and signed AMP update cache URL from the function above. Here are Google's docs on the process with examples of what the cache URL should look like.