helper.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from urllib.parse import quote, urlencode
  5. from datetime import datetime
  6. from pytz import timezone
  7. import requests
  8. import hashlib
  9. import base64
  10. import random
  11. import time
  12. import hmac
  13. import uuid
  14. def _special_url_encode(value) -> str:
  15. if isinstance(value, (str, bytes)):
  16. rst = quote(value)
  17. else:
  18. rst = urlencode(value)
  19. return rst.replace('+', '%20').replace('*', '%2A').replace('%7E', '~')
  20. def _make_ali_signature(key: str, params: dict) -> bytes:
  21. sorted_str = _special_url_encode(dict(sorted(params.items())))
  22. sign_str = 'GET&%2F&' + _special_url_encode(sorted_str)
  23. sign_digest = hmac.new(key.encode(), sign_str.encode(), hashlib.sha1).digest()
  24. return base64.encodebytes(sign_digest).strip()
  25. def _make_tencent_signature(endpoint: str, key: str, params: dict) -> bytes:
  26. sorted_str = '&'.join(f'{k}={v}' for k, v in sorted(params.items()))
  27. sign_str = f'POST{endpoint}/?{sorted_str}'
  28. sign_digest = hmac.new(key.encode(), sign_str.encode(), hashlib.sha1).digest()
  29. return base64.encodebytes(sign_digest).strip()
  30. def make_ali_request(ak, ac, endpoint, params):
  31. params.update(
  32. AccessKeyId=ak,
  33. Format='JSON',
  34. SignatureMethod='HMAC-SHA1',
  35. SignatureNonce=uuid.uuid4().hex,
  36. SignatureVersion='1.0',
  37. Timestamp=datetime.now(tz=timezone('UTC')).strftime('%Y-%m-%dT%H:%M:%SZ'),
  38. Version='2014-05-26'
  39. )
  40. params['Signature'] = _make_ali_signature(ac + '&', params)
  41. return requests.get(endpoint, params).json()
  42. def make_tencent_request(ak, ac, endpoint, params):
  43. params.update(
  44. Nonce=int(random.random() * 10000),
  45. SecretId=ak,
  46. Timestamp=int(time.time()),
  47. Version='2017-03-12'
  48. )
  49. params['Signature'] = _make_tencent_signature(endpoint, ac, params)
  50. return requests.post(f'https://{endpoint}', data=params).json()