tools.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import json
  2. import xml.etree.ElementTree as ET
  3. import aiohttp
  4. import requests
  5. def _xml_to_dict(element):
  6. if len(element) == 0:
  7. return element.text
  8. return {child.tag: _xml_to_dict(child) for child in element}
  9. def xml_parser(xml_str: str):
  10. xml_root = ET.fromstring(xml_str)
  11. obj = _xml_to_dict(xml_root)
  12. return obj
  13. def xml_build(root_text: str, data: object):
  14. root = ET.Element(root_text)
  15. for key in data.__dir__():
  16. if not key.startswith('__'):
  17. value = getattr(data, key)
  18. if not callable(value) and value is not None:
  19. item = ET.SubElement(root, key)
  20. item.text = str(value)
  21. return root
  22. def xml_to_string(root: ET.Element):
  23. return ET.tostring(root, encoding='utf-8').decode('utf-8')
  24. def __get_access_token__():
  25. url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf01ec97b45a4bc49&secret=ee1681fc5d4bfe8797de9c61ff15f08b"
  26. rsp = requests.get(url)
  27. obj = json.loads(rsp.text)
  28. return obj['access_token']
  29. def sync_post(url: str, body: object):
  30. return requests.post(url=url, json=body)
  31. async def post_as_normal(url: str, headers: object, body: object):
  32. async with aiohttp.ClientSession() as session:
  33. async with session.post(url, headers=headers, json=body) as response:
  34. return await response.text()