You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyJWT生成APNs令牌遇双重错误:str无decode/bytes无法JSON序列化

APNS JWT生成与请求序列化问题

我正在为Apple推送通知服务(APNS)生成请求用的JWT,参考了两段Gist代码实现。按照这些代码的做法,我尝试对jwt.encode()生成的令牌执行解码操作,但根据PyJWT官方文档,该方法返回的是字符串类型,Stack Overflow上的类似问题也验证了这一点,所以我不确定解码的必要性。

错误场景1:不解码令牌时的TypeError

如果不对令牌解码,将其放入请求头后会触发TypeError: Object of type bytes is not JSON serializable错误,代码如下:

def generate_token() -> str:
    token = jwt.encode(
        {...}  # 此处省略JWT的payload和密钥等参数
    )

    return token

def push_notification():
    auth_token = generate_token()
    headers = {"authorization": f"Bearer {auth_token}"}
    ...
    response = await client.post(url, headers=headers, json=payload)  # 此处触发TypeError

错误场景2:解码令牌时的AttributeError

如果尝试对令牌执行解码操作,会抛出AttributeError: 'str' object has no attribute 'decode'错误,代码片段:

"authorization": f"bearer {auth_token.decode('ascii')}" 
# 报错:AttributeError: 'str' object has no attribute 'decode'

补充说明:Payload的构成

需要说明的是,传入请求的payload参数由纯字符串字典组成,本身不存在bytes类型,但我做了手动序列化编码:

payload_data = {
    "aps": {
        "alert": {
            "title": "Air Quality Alert",
            "subtitle": "Your Air Quality Has recently exceeded WHO guidelines",
            "body": "This is a test notification"
        },
        "sound": "default",
        "category": "AIR_QUALITY",
        "interruption-level": "active"
    },
}

payload = json.dumps(payload_data).encode('utf-8')

解决方案

问题的核心出在payload的处理和对JWT返回值的误解:

  1. 修正Payload传递方式:client.post的json参数接受Python字典类型,会自动完成JSON序列化和编码操作,不需要手动调用json.dumps()和encode('utf-8')。直接传入payload_data即可,避免将bytes类型传入json参数导致序列化错误。
  2. JWT令牌直接使用:PyJWT的jwt.encode()返回的是字符串类型,无需执行decode()操作,直接拼接进请求头即可。

修正后的关键代码:

def push_notification():
    auth_token = generate_token()
    headers = {"authorization": f"Bearer {auth_token}"}
    ...
    # 直接传入Python字典,无需手动序列化编码
    response = await client.post(url, headers=headers, json=payload_data)

内容的提问来源于stack exchange,提问作者John Harrington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:45:54