阿里云openapi签名实现代码(基于Python)

简介: 部分开发者在接触阿里云openAPi调用的时候,Signature的构造和生成一直都是一只拦路虎,本文中将基于Python,和点播的APi:getPlayAuth 实现签名的构造,仅供大家参考。

strToSign的构造过程以如下流程简要说明:
image.png

product.json文件内容
{
    "vod":{
      "Format":"JSON",
      "Version":"2017-03-21",
      "AccessKeyId":"yourAccessKeyID",
      "SignatureMethod":"HMAC-SHA1",
      "SignatureVersion":"1.0"
    }
  }

代码正文:

# coding=utf-8
import json
import uuid
import datetime
import hmac
import base64
from urllib import quote
import hashlib


class SignatureUrl():
    """python 计算openapi的签名"""

    def __init__(self, public_param, private_param):
        self.public_param = public_param
        self.private_param = private_param

    def get_timestamp(self):
        time_format = "%Y-%m-%dT%H:%M:%SZ"
        return datetime.datetime.utcnow().strftime(time_format)

    def get_uuid(self):
        return str(uuid.uuid1())

    def url_encode_str(self, all_params):
        sort_all_params = list()
        for key, value in all_params.items():
            params = key + '=' + value
            sort_all_params.append(params)
        # 对参数进行升序排序
        sort_all_params.sort()

        for i in range(len(sort_all_params)):
            # 对参数以及参数值进行urlencode处理,注意:’=‘此时不能处理,否则后面会再次对%3D进行encode
            sort_all_params[i] = quote(sort_all_params[i], '=')
            # 对encode之后的字符串进行再处理
            tmp = sort_all_params[i]
            if tmp.find('+'):
                tmp.replace('+','%20')
            elif tmp.find('*'):
                tmp.replace('*','%2A')
            elif tmp.find('%7E'):
                tmp.replace('%7E','~')
            
            sort_all_params[i] = tmp
        return sort_all_params

    def get_signature(self, param, http_method,AccesskeySecret):
        str_to_sign = ''
        sort_all_params = self.url_encode_str(param)
        print(sort_all_params)
        for i in range(len(sort_all_params)):
            str_to_sign = str_to_sign + sort_all_params[i] + '&'

        # 将最后一位&给截取掉
        str_to_sign = http_method + '&%2F&' + quote(str_to_sign[:-1])
        print(str_to_sign)
        key = AccesskeySecret+'&'
        signature = hmac.new(key.encode(
            'utf-8'), str_to_sign.encode('utf-8'), digestmod=hashlib.sha1)
        signature = base64.b64encode(signature.digest())
        # 解决签名中包含有'+'的特殊情况
        signature = list(signature)
        for i in range(len(signature)):
            if signature[i] == '+':
                signature[i] = '%2B'
        newSignature = ''.join(signature)
        self.private_param['Signature'] = newSignature

    def url_factory(self):
        all_params = dict(self.public_param, **self.private_param)
        self.get_signature(all_params, 'GET','yourAccessKeySecret')
        url = 'http://vod.cn-shanghai.aliyuncs.com' + '?AccessKeyId=' + self.public_param['AccessKeyId'] + '&Action=' + self.private_param['Action'] + '&Format=' + self.public_param['Format'] + '&Version=' + self.public_param['Version'] + '&SignatureMethod=' + self.public_param['SignatureMethod'] + \
            '&SignatureVersion=' + self.public_param['SignatureVersion'] + '&Timestamp=' + self.public_param['Timestamp'] + '&SignatureNonce=' + \
            self.public_param['SignatureNonce'] + '&VideoId=' + \
            self.private_param['VideoId'] + '&Signature=' + self.private_param['Signature']
        print('url is : ' + url)


public_param = dict()
private_param = dict()
pubduct = 'vod'
with open("/Users/storageuser/PycharmProjects/openapiPython/product.json", "r") as param:
    files = json.load(param)
    #public_param["Endpoint"] = files[pubduct]["Endpoint"].encode("utf-8")
    public_param["Format"] = files[pubduct]["Format"].encode("utf-8")
    public_param["Version"] = files[pubduct]["Version"].encode("utf-8")
    public_param["AccessKeyId"] = files[pubduct]["AccessKeyId"].encode("utf-8")
    public_param["SignatureMethod"] = files[pubduct]["SignatureMethod"].encode("utf-8")
    public_param["SignatureVersion"] = files[pubduct]["SignatureVersion"].encode("utf-8")
    action_param = dict()
    action_param["VideoId"] = "f6a21eade82f4cf6b45669fa34b35b76"
    action_param["Action"] = "GetVideoPlayAuth"
    private_param["Action"] = action_param["Action"]
    private_param["VideoId"] = action_param["VideoId"]

sig = SignatureUrl(public_param, private_param)
sig.public_param["Timestamp"] = sig.get_timestamp()
sig.public_param["SignatureNonce"] = sig.get_uuid()

sig.url_factory()
相关文章
|
1月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
236 100
|
1月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
368 95
|
2月前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
237 104
|
2月前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
432 99
|
1月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
153 88
|
1月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。
|
2月前
|
设计模式 人工智能 API
AI智能体开发实战:17种核心架构模式详解与Python代码实现
本文系统解析17种智能体架构设计模式,涵盖多智能体协作、思维树、反思优化与工具调用等核心范式,结合LangChain与LangGraph实现代码工作流,并通过真实案例验证效果,助力构建高效AI系统。
424 7
|
JavaScript API 开发工具
阿里云OpenAPI AssignJobs返回404错误可能有以下几个原因:
【2月更文挑战第20天】阿里云OpenAPI AssignJobs返回404错误可能有以下几个原因:
325 1
|
域名解析 弹性计算 tengine
阿里云DNS常见问题之阿里云OpenAPI判断域名的dns服务器是否在阿里云失败如何解决
阿里云DNS(Domain Name System)服务是一个高可用和可扩展的云端DNS服务,用于将域名转换为IP地址,从而让用户能够通过域名访问云端资源。以下是一些关于阿里云DNS服务的常见问题合集:
|
云安全 安全 API
阿里云——OpenAPI使用——短信服务
阿里云——OpenAPI使用——短信服务
593 0

推荐镜像

更多