阿里云智能云相册

master
10295 6 years ago
parent d035e5e206
commit a8962d052d
  1. 135
      PixivSearch/aliyun/photo/AliyunPhoto.py

@ -1,16 +1,26 @@
import base64
import calendar
import datetime
import hashlib
import hmac
import json
import os
import random
from urllib import parse
import requests
import aliyunsdkcore
import oss2 as oss2
from aliyunsdkcore.client import AcsClient, DEFAULT_SDK_CONNECTION_TIMEOUT_IN_SECONDS
from aliyunsdkcore.request import CommonRequest
def get_md5_01(file_path):
class UploadPhoto(AcsClient):
def __init__(self, ak='LTAIeS8aBuPBZxV2', secret='hyPeTaDQBQs6jetYcqY0BUdpacXTH3', region_id="cn-hongkong",
auto_retry=True, max_retry_time=3,
user_agent=None, port=80, timeout=DEFAULT_SDK_CONNECTION_TIMEOUT_IN_SECONDS, public_key_id=None,
private_key=None, session_period=3600, credential=None, debug=False):
super().__init__(ak, secret, region_id, auto_retry, max_retry_time, user_agent, port, timeout, public_key_id,
private_key, session_period, credential, debug)
aliyunsdkcore.request.set_default_protocol_type("https")
self.domain='cloudphoto.cn-shanghai.aliyuncs.com'
self.version='2017-07-11'
def get_md5_01(self, file_path):
md5 = None
if os.path.isfile(file_path):
f = open(file_path, 'rb')
@ -21,43 +31,78 @@ def get_md5_01(file_path):
md5 = str(hash_code).lower()
return md5
def assumeRole(self):
request = CommonRequest(domain='sts.aliyuncs.com', version='2015-04-01',
action_name='AssumeRole')
RoleSessionName = 'pqh'
request.add_query_param('RoleArn', 'acs:ram::1098806312754985:role/aliyuncloudphotodefaultrole')
request.add_query_param('RoleSessionName', RoleSessionName)
response = json.loads(self.do_action_with_exception(request).decode())
print(response['Credentials']['SecurityToken'])
def createTransaction(HTTPMethod, filePath):
fileName = filePath.split('/')[-1]
param = {
# "Format": "JSON",
"Version": '2017-07-11',
"AccessKeyId": "LTAIeS8aBuPBZxV2",
"SignatureMethod": "HMAC-SHA1",
"Timestamp": datetime.datetime.utcnow().isoformat()[:19] + 'Z',
"SignatureVersion": "1.0",
"SignatureNonce": '9166ab59-f445-' + str(random.randint(1000, 9999)) + '-911d-664c1570df0f',
"Action": "CreateTransaction"
# "Ext": fileName[-fileName[::-1].index('.'):],
# "Md5": get_md5_01(filePath),
# "Size": os.path.getsize(filePath)
}
AccessKeySecret = b'hyPeTaDQBQs6jetYcqY0BUdpacXTH3&'
canonicalQueryString = ''
for i in sorted(param.items(), key=lambda d: d[0]):
canonicalQueryString += '&' + i[0] + '=' + str(i[1])
print(canonicalQueryString[1:])
strUrlEncoding = HTTPMethod + '&%2F&' + parse.quote(canonicalQueryString[1:])
print(strUrlEncoding)
stringToSign = base64.b64encode(hmac.new(AccessKeySecret, strUrlEncoding.encode('UTF-8'), 'sha1').digest())
print(stringToSign)
server = 'https://cloudphoto.cn-shanghai.aliyuncs.com'
url = server + "?" + canonicalQueryString[1:] + '&Signature=' + parse.quote(stringToSign.decode('utf-8')).replace(
'/', '%2F')
print(url)
result = requests.get(url)
print(result.content)
def createAction(self,action):
return CommonRequest(domain=self.domain, version=self.version,
action_name=action)
if __name__ == '__main__':
createTransaction("GET", "C:/Users/10295/Desktop/灵梦.png")
# print(datetime.datetime.utcnow())
# createTransaction("GET", "C:/Users/10295/Desktop/灵梦.png")
client = UploadPhoto()
request = client.createAction('ListPhotoStores')
response = json.loads(client.do_action_with_exception(request).decode())
print(response)
print('PhotoStores:')
photoStores = response['PhotoStores']
for index, photoStore in enumerate(photoStores):
print('{index}:{name}'.format(index=index + 1, name=photoStore['Name']))
StoreName = input('输入StoreName\n')
# request = client.createAction('GetPhotoStore')
# request.set_accept_format('json')
# request.add_query_param('StoreName', StoreName)
# response = json.loads(client.do_action_with_exception(request).decode())
# print(response)
# buckets = response['PhotoStore']['Buckets']
#
# request = client.createAction('CreateTransaction')
# filePath = 'C:/Users/10295/Desktop/灵梦.png'
# fileName = filePath.split('/')[-1]
# request.add_query_param('Size', os.path.getsize(filePath))
# request.add_query_param('Ext', fileName[-fileName[::-1].index('.'):])
# request.add_query_param('Md5', client.get_md5_01(filePath))
# request.add_query_param('StoreName', StoreName)
#
# liberaryId = input('输入liberaryId\n')
# request.add_query_param('LibraryId', liberaryId)
# response = json.loads(client.do_action_with_exception(request))
# print(response)
#
# Upload=response['Transaction']['Upload']
# FileId = Upload['FileId']
# SessionId = Upload['SessionId']
# Bucket=Upload['Bucket']
# OssEndpoint=Upload['OssEndpoint']
# ObjectKey=Upload['ObjectKey']
#
# auth = oss2.Auth(client.get_access_key(), client.get_access_secret())
# bucket = oss2.Bucket(auth, OssEndpoint,Bucket)
# with open(filePath, 'rb') as fileobj:
# result=bucket.put_object(ObjectKey,fileobj)
# print('文件上传状态{status}'.format(status=result.status))
#
# request = client.createAction('CreatePhoto')
# request.add_query_param('FileId', FileId)
# request.add_query_param('PhotoTitle', fileName)
# request.add_query_param('SessionId', SessionId)
# request.add_query_param('StoreName', StoreName)
# request.add_query_param('UploadType', 'manual')
# request.add_query_param('LibraryId', liberaryId)
# response = json.loads(client.do_action_with_exception(request))
# print(response)
request=client.createAction('FetchLibraries')
request.add_query_param('StoreName', StoreName)
request.add_query_param('LibraryId', '')
response = json.loads(client.do_action_with_exception(request))
print(response)
Loading…
Cancel
Save