48 lines
1.8 KiB
Python
48 lines
1.8 KiB
Python
import hmac
|
|
from hashlib import sha1
|
|
import base64
|
|
import time
|
|
import uuid
|
|
import requests
|
|
import Config.Config
|
|
|
|
|
|
class LiblibUtil:
|
|
def __init__(self):
|
|
self.base_url = Config.Config.LIBLIB_URL
|
|
self.access_key = Config.Config.LIBLIB_ACCESSKEY
|
|
self.secret_key = Config.Config.LIBLIB_SECRETKEY
|
|
self.timeout = 30
|
|
|
|
def make_sign(self, uri):
|
|
"""生成API请求签名"""
|
|
timestamp = str(int(time.time() * 1000))
|
|
signature_nonce = str(uuid.uuid4())
|
|
content = '&'.join((uri, timestamp, signature_nonce))
|
|
|
|
digest = hmac.new(self.secret_key.encode(), content.encode(), sha1).digest()
|
|
sign = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()
|
|
return sign, timestamp, signature_nonce
|
|
|
|
def post_request(self, uri, payload):
|
|
"""发送POST请求到Liblib API"""
|
|
try:
|
|
sign, timestamp, signature_nonce = self.make_sign(uri)
|
|
url = f'{self.base_url}{uri}?AccessKey={self.access_key}&Signature={sign}&Timestamp={timestamp}&SignatureNonce={signature_nonce}'
|
|
|
|
headers = {'Content-Type': 'application/json'}
|
|
response = requests.post(url, json=payload, headers=headers, timeout=self.timeout)
|
|
response.raise_for_status()
|
|
|
|
response_data = response.json()
|
|
if response_data.get('code') == 0:
|
|
return response_data.get('data')
|
|
else:
|
|
print(f"API错误: {response_data.get('message')}")
|
|
return None
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"请求异常: {str(e)}")
|
|
return None
|
|
except Exception as e:
|
|
print(f"处理异常: {str(e)}")
|
|
return None |