吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1205|回复: 2
收起左侧

[求助] 求大佬帮忙将“视频点播如何通过Python实现OpenAPI构造签名”python2的代码转换

[复制链接]
pwp 发表于 2021-3-6 16:04
求大佬帮忙将“视频点播如何通过Python实现OpenAPI构造签名”python2的代码转换成python3

概述本文主要介绍如何通过Python实现OpenAPI构造签名。详细信息若product.json文件内容如下所示。
[JavaScript] 纯文本查看 复制代码
{
    "vod":{
      "Format":"JSON",
      "Version":"2017-03-21",
      "AccessKeyId":"yourAccessKeyID",
      "SignatureMethod":"HMAC-SHA1",
      "SignatureVersion":"1.0"
    }
}


则通过Python实现OpenAPI签名构造的示例如下所示。

[Python] 纯文本查看 复制代码
# 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()

没能正常运行起来
测试视频信息:
[JavaScript] 纯文本查看 复制代码
AccessKeyId: STS.NSxJH4LTwZ3hD1yrmTQvAyaHg
Action: GetPlayInfo
AuthInfo: {"CI":"s6xYzXG1nJZMZKszaWtcEbPRgmOIYAVv47TWMReTHAyB2aFUS6vBl1dDLCPB5O2K+ATHewyiVrNFxN1zydLlCKFZD/RolO0FwFGPksecw1g=","Caller":"e8JxYI2mwrac+uy11f0idU5SpwFISiRrAbj+hH9I6qo=","ExpireTime":"2021-03-06T07:30:58Z","MediaId":"e9bfcc430801454a9c38c4ff85f3e6af","PlayDomain":"video.**.com","Signature":"3QT1++mbkr0OgWmffZ1vGzfVpUk="}
AuthTimeout: 7200
Channel: HTML5
Definition: 
Format: JSON
Formats: 
PlayConfig: {}
PlayerVersion: 2.8.2
Rand: C/g952dkwCauhzWoZpFbR6qi4GYjdx8xcL0Etkh1eguC8BdsE+7OXXou68r49jlsiH0Gc7xh18kE/zOY1QFcsw==
ReAuthInfo: {}
SecurityToken: CAIShwN1q6Ft5B2yfSjIr5DNAfKAoYtW7fGDRhfIlm0BXfltlqTjhTz2IHlPe3FhAOoev/k/mW9U7foclrMqGsMdGBOUMZMvt80NqV78JpLFst2J6r8JjsUy641O41mpsvXJasDVEfl2E5XEMiIR/00e6L/+cirYpTXHVbSClZ9gaPkOQwC8dkAoLdxKJwxk2t14UmXWOaSCPwLShmPBLUxmvWgGl2Rzu4uy3vOd5hfZp1r8xO4axeL0PoP2V81lLZplesqp3I4Sc7baghZU4glr8qlx7spB5SyVktyWGUhJ/zaLIoit7NpjfiB0eoQAPopFp/X6jvAawPLUm9bYxgphB8R+Xj7DZYaux7GzeoWTO80+aKzwNlnUz9mLLeOViQ4/Zm8BPw44ELhIaF0IUEJ8G2CCd/X4oguSOln9EJLoiv9mjcBHqHzz5sePKlS1RLGU7D0VIJdUbTlzbkVJhT24KPdXLlwRLA88W+iPMax3bQFDr53vsTbbXzZb0mptuPnzd2x2BBOsn22UGoABr7C2de3Gj3odlDv0JZh5wYioojxygzTDJ28NWPnZ7IrlhoQpeK5xedbcVZmDZYvgRBLLg7DWCAQX7mInYq1PyNz6qC6bb6Z/o2Y5qT+uImfYDp9x+ECUwjqmgVdhOUCidiGi/On7bNvqq0nkTT8wifb2SC8b5xvo051W7b2czuE=
SignatureMethod: HMAC-SHA1
SignatureNonce: ae7d68a2-3747-4bc1-999a-31e1b74103de
SignatureVersion: 1.0
StreamType: video
Version: 2017-03-21
VideoId: e9bfcc430801454a9c38c4ff85f3e6af
Signature: F/s3Gzi8nKG9Ne6oJ7q5hsE7pqA=

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
chensweet + 1 + 1 热心回复!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| pwp 发表于 2021-3-6 16:07
[Python] 纯文本查看 复制代码
from urllib.parse import quote
Light紫星 发表于 2021-3-6 17:28
python有个叫six的模块支持2和3之间的转换,转换后自己再稍微修改一下就行
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-26 07:46

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表