py之阿里云机器翻译接口实现


import base64
import hashlib
import hmac
import uuid
from datetime import datetime
from urllib.parse import urlparse
import requests
import json


class Sender:
    """
    阿里云API请求发送器 - Python版本
    """

    @staticmethod
    def MD5Base64(s):
        """
        计算MD5+BASE64
        """
        if s is None:
            return None
        try:
            # 计算MD5
            md5_bytes = hashlib.md5(s.encode()).digest()
            # Base64编码
            base64_str = base64.b64encode(md5_bytes).decode()
            return base64_str
        except Exception as e:
            raise Exception("Failed to generate MD5 : " + str(e))

    @staticmethod
    def HMACSha1(data, key):
        """
        计算 HMAC-SHA1
        """
        try:
            # 创建HMAC-SHA1签名
            signing_key = key.encode()
            mac = hmac.new(signing_key, data.encode(), hashlib.sha1)
            # Base64编码
            raw_hmac = mac.digest()
            base64_str = base64.b64encode(raw_hmac).decode()
            return base64_str
        except Exception as e:
            raise Exception("Failed to generate HMAC : " + str(e))

    @staticmethod
    def toGMTString(date):
        """
        获取GMT格式的时间字符串
        """
        # Python中的格式化与Java略有不同
        return date.strftime("%a, %d %b %Y %H:%M:%S GMT")

    @staticmethod
    def sendPost(url, body, ak_id, ak_secret):
        """
        发送POST请求
        """
        result = ""
        try:
            # 解析URL获取路径和主机名
            parsed_url = urlparse(url)

            path = parsed_url.path
            if parsed_url.query:
                path += "?" + parsed_url.query
            print("path:",path)
            host = parsed_url.hostname

            # 准备请求参数
            method = "POST"
            accept = "application/json"
            content_type = "application/json;chrset=utf-8"
            date = Sender.toGMTString(datetime.utcnow())
            print(date)
            # 1.对body做MD5+BASE64加密
            body_md5 = Sender.MD5Base64(body)
            uuid_str = str(uuid.uuid4())

            # 构建待签名字符串
            string_to_sign = (
                f"{method}\n{accept}\n{body_md5}\n{content_type}\n{date}\n"
                f"x-acs-signature-method:HMAC-SHA1\n"
                f"x-acs-signature-nonce:{uuid_str}\n"
                f"x-acs-version:2019-01-02\n"
                f"{path}"
            )
            # 2.计算 HMAC-SHA1
            signature = Sender.HMACSha1(string_to_sign, ak_secret)
            # 3.得到 authorization header
            auth_header = f"acs {ak_id}:{signature}"
            # 设置请求头
            headers = {
                "Accept": accept,
                "Content-Type": content_type,
                "Content-MD5": body_md5,
                "Date": date,
                "Host": host,
                "Authorization": auth_header,
                "x-acs-signature-nonce": uuid_str,
                "x-acs-signature-method": "HMAC-SHA1",
                "x-acs-version": "2019-01-02"
            }
            # 发送POST请求
            response = requests.post(
                url,
                data=body.encode('utf-8'),
                headers=headers,
                timeout=30
            )
            # 处理响应
            result = response.text

        except Exception as e:
            print("发送 POST 请求出现异常!", e)
            raise e

        return result


# 使用示例
if __name__ == "__main__":
    serviceURL = "http://mt.cn-hangzhou.aliyuncs.com/api/translate/web/ecommerce"
    accessKeyId = ""  # 使用您的阿里云访问密钥 AccessKeyId
    accessKeySecret = ""  # 使用您的阿里云访问密钥
    postBody = json.dumps({
        "FormatType": "text",
        "SourceLanguage": "zh",
        "TargetLanguage": "en",
        "SourceText": "我不是萧海哇",
        "Scene": "title"
    }, ensure_ascii=False)

    result = Sender.sendPost(serviceURL, postBody, accessKeyId, accessKeySecret)
    print(result)

测试效果:
image

目标网址

posted @ 2025-08-23 11:02  我不是萧海哇~~~  阅读(14)  评论(0)    收藏  举报