#!/usr/env/bin python
import base64
import hashlib
import hmac
import urllib
import urllib2
from base64 import urlsafe_b64encode, urlsafe_b64decode
from urlparse import urlparse
AK =""
SK =""
HUB="直播的hub名"
StreamKey="直播的key流名"
snapshotFileName="截图的文件名"
//这里使用装饰器
def HTTP_CURL(function):
def func(*agrs,**data):
req = function(*agrs,**data)
data = urllib2.urlopen(req)
return data
return func
@HTTP_CURL
def getHTTPHeader(url,header = None,value=None):
if value ==None:
req =urllib2.Request(url)
else:
data =value
req = urllib2.Request(url,data)
for (k,v) in header.items():
req.add_header(k,v)
return req
def urlsafe_base64_decode(data):
ret = urlsafe_b64decode(s(data))
return ret
def s(data):
if isinstance(data, bytes):
data = data.decode('utf-8')
return data
//鉴权的生成
def MACToken(AK,SK,URL,Conetnt,Body=None,Methon=None):
parsed = urlparse(URL)
raw_str = '%s %s' % (Methon, parsed.path)
if parsed.query:
raw_str += '?%s' % (parsed.query)
raw_str += '\nHost: %s' % (parsed.netloc)
if Body:
raw_str += '\nContent-Type: application/json'
raw_str += "\n\n"
if Body:
raw_str += Body
Authdata = __hmac_sha1__(raw_str, SK)
print raw_str
return " Qiniu "+AK+":"+Authdata
def __hmac_sha1__(data, key):
"""
hmac-sha1
"""
hashed = hmac.new(key, data, hashlib.sha1)
return base64.urlsafe_b64encode(hashed.digest())
def main():
key=base64.urlsafe_b64encode(StreamKey)
url="http://pili.qiniuapi.com/v2/hubs/%s/streams/%s/snapshot"%(HUB,key)
postdata='{"fname": "%s"}'%(snapshotFileName)
AUTHS=MACToken(AK,SK,url,"Content-Type: application/json",postdata,"POST")
print AUTHS
myheader = {"Authorization": str(AUTHS), "User-Agent": "Python-urllib/2.7", "Content-Type": "application/json"}
data=getHTTPHeader( url=url, header=myheader,value=postdata)
print data.read()
if __name__ == '__main__':
main()
其实鉴权是都是一样参考这里
// 构造待签名的 Data
// 1. 添加 Path
data = " "
// 2. 添加 Query,前提: Query 存在且不为空
if "" != "" {
data += "?"
}
// 3. 添加 Host
data += "\nHost: "
// 4. 添加 Content-Type,前提: Content-Type 存在且不为空
if "" != "" {
data += "\nContent-Type: "
}
// 5. 添加回车
data += "\n\n"
// 6. 添加 Body,前提: Content-Length 存在且 Body 不为空,同时 Content-Type 存在且不为空或 "application/octet-stream"
bodyOK := "" != "" && "" != ""
contentTypeOK := "" != "" && "" != "application/octet-stream"
if bodyOK && contentTypeOK {
data += ""
}
// 计算 HMAC-SHA1 签名,并对签名结果做 URL 安全的 Base64 编码
sign = hmac_sha1(data, "Your_Secret_Key")
encodedSign = urlsafe_base64_encode(sign)
// 将 Qiniu 标识与 AccessKey、encodedSign 拼接得到管理凭证
<QiniuToken> = "Qiniu " + "Your_Access_Key" + ":" + encodedSign