requests_utils.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #
  2. # Copyright 2021 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import functools
  17. import json
  18. from base64 import b64encode
  19. from hmac import HMAC
  20. from time import time
  21. from urllib.parse import quote, urlencode
  22. from uuid import uuid1
  23. import requests
  24. from fate_arch.common.base_utils import CustomJSONEncoder
  25. from fate_flow.settings import CLIENT_AUTHENTICATION, HTTP_APP_KEY, HTTP_SECRET_KEY
  26. requests.models.complexjson.dumps = functools.partial(json.dumps, cls=CustomJSONEncoder)
  27. def request(**kwargs):
  28. sess = requests.Session()
  29. stream = kwargs.pop('stream', sess.stream)
  30. timeout = kwargs.pop('timeout', None)
  31. kwargs['headers'] = {k.replace('_', '-').upper(): v for k, v in kwargs.get('headers', {}).items()}
  32. prepped = requests.Request(**kwargs).prepare()
  33. if CLIENT_AUTHENTICATION and HTTP_APP_KEY and HTTP_SECRET_KEY:
  34. timestamp = str(round(time() * 1000))
  35. nonce = str(uuid1())
  36. signature = b64encode(HMAC(HTTP_SECRET_KEY.encode('ascii'), b'\n'.join([
  37. timestamp.encode('ascii'),
  38. nonce.encode('ascii'),
  39. HTTP_APP_KEY.encode('ascii'),
  40. prepped.path_url.encode('ascii'),
  41. prepped.body if kwargs.get('json') else b'',
  42. urlencode(sorted(kwargs['data'].items()), quote_via=quote, safe='-._~').encode('ascii')
  43. if kwargs.get('data') and isinstance(kwargs['data'], dict) else b'',
  44. ]), 'sha1').digest()).decode('ascii')
  45. prepped.headers.update({
  46. 'TIMESTAMP': timestamp,
  47. 'NONCE': nonce,
  48. 'APP-KEY': HTTP_APP_KEY,
  49. 'SIGNATURE': signature,
  50. })
  51. return sess.send(prepped, stream=stream, timeout=timeout)