__init__.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #-*- coding:utf-8 -*-
  2. # Copyright 2017 Xiaomi, Inc.
  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. import requests
  16. import json
  17. def auth_requests(method, *args, **kwargs):
  18. from flask import g
  19. if not g.user_token:
  20. raise Exception("no api token")
  21. headers = {
  22. "Apitoken": json.dumps({"name":g.user_token.name, "sig":g.user_token.sig})
  23. }
  24. if not kwargs:
  25. kwargs = {}
  26. if "headers" in kwargs:
  27. headers.update(kwargs["headers"])
  28. del kwargs["headers"]
  29. if method == "POST":
  30. return requests.post(*args, headers=headers, **kwargs)
  31. elif method == "GET":
  32. return requests.get(*args, headers=headers, **kwargs)
  33. elif method == "PUT":
  34. return requests.put(*args, headers=headers, **kwargs)
  35. elif method == "DELETE":
  36. return requests.delete(*args, headers=headers, **kwargs)
  37. else:
  38. raise Exception("invalid http method")