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

Azure Python函数应用队列触发器读取消息时出现编码错误

问题解决:Azure Functions队列消息解码及Unicode打印错误

错误根源分析

从报错栈可以明确两个核心问题:

  1. 队列消息解码逻辑不匹配:发送消息时使用BinaryBase64EncodePolicy对字节流做Base64编码,但接收时直接调用get_body().decode('utf-8')未先解码Base64,逻辑流程不对应。
  2. Unicode字符打印失败:Windows终端默认编码为CP1252,无法编码\u2212(Unicode长减号字符),而fetch_set_data返回的set_data包含该字符,执行print(set_data)时触发UnicodeEncodeError。

解决方案

1. 修正队列消息解码逻辑

接收消息时必须对应发送时的编码策略,先解码Base64再转成字符串:

from azure.storage.queue import BinaryBase64DecodePolicy

def main(queueImportSetCards: func.QueueMessage) -> None:
    start = time.perf_counter()
    logger.info('Get Set - Cards: Started.')

    # 初始化Base64解码策略
    decode_policy = BinaryBase64DecodePolicy()
    # 先解码Base64得到原始字节流,再转成UTF-8字符串
    message_bytes = decode_policy.decode(queueImportSetCards.get_body())
    message_content = message_bytes.decode('utf-8')
    logger.info(f"Received message: {message_content}")

    with DatabaseManager() as db:
        set_data = fetch_set_data(message_content)
        # 后续业务逻辑...

2. 解决Unicode字符打印/日志问题

推荐使用Azure Functions内置的logger替代print,logger默认支持Unicode字符,不会出现编码错误:

# 替换原print(set_data)为:
logger.info(f"Fetched set data: {set_data}")

若必须使用print,可强制设置标准输出编码为UTF-8:

import sys

def main(queueImportSetCards: func.QueueMessage) -> None:
    # 开头添加此行,强制stdout使用UTF-8编码
    sys.stdout.reconfigure(encoding='utf-8')
    start = time.perf_counter()
    logger.info('Get Set - Cards: Started.')

    # ... 其他代码 ...

    print(set_data)  # 现在可正常打印含Unicode的内容

可选优化:简化队列消息编码逻辑

如果消息仅为普通字符串,无需手动设置BinaryBase64EncodePolicy,QueueClient默认的TextBase64EncodePolicy更适配字符串场景:

# 发送函数简化代码
queue_client = QueueClient.from_connection_string(connection_string, queue_name)
# 直接发送字符串,无需手动转字节流和编码
queue_client.send_message(code)

此时接收函数可直接解码:

message_content = queueImportSetCards.get_body().decode('utf-8')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:15:55