IPWeatherObject.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # @Author : Rocky
  2. # @File : IPWeatherObject.py
  3. # @Time : 2023/8/16 8:56
  4. import requests
  5. class IPQuery:
  6. """
  7. 阿里云IP地址查询
  8. https://market.aliyun.com/products/57002003/cmapi021970.html?spm=5176.2020520132.recommend-card.dbottom-suggestion.33e17218GYjWDt#sku=yuncode15970000020
  9. """
  10. def __init__(self, ip):
  11. self.appcode = 'd7d63b34b1d54214be446608a57ff0a2'
  12. self.host = 'https://c2ba.api.huachen.cn'
  13. self.path = '/ip'
  14. self.district = None
  15. self.country_id = None
  16. param = 'ip=' + ip
  17. url = self.host + self.path + '?' + param
  18. # 获取ip的区级和城市信息
  19. headers = {'Authorization': 'APPCODE ' + self.appcode}
  20. res = requests.get(url=url, headers=headers)
  21. if res.status_code == 200:
  22. # 反序列化响应数据
  23. res_data = eval(res.content.decode('utf-8'))
  24. if res_data['ret'] == 200:
  25. district = res_data['data']['district']
  26. city = res_data['data']['city'] + '市'
  27. country_id = res_data['data']['country_id']
  28. self.district = district if district else city
  29. self.country_id = country_id
  30. class WeatherInfo:
  31. def __init__(self, city_id):
  32. self.appcode = 'd7d63b34b1d54214be446608a57ff0a2'
  33. self.headers = {'Authorization': 'APPCODE ' + self.appcode,
  34. 'Content-Type': 'application/x-www-form-urlencoded'}
  35. self.city_id = city_id
  36. def get_city_weather(self):
  37. url = "https://aliv18.data.moji.com/whapi/json/alicityweather/condition" # 获取实时天气
  38. data = {'cityId': self.city_id}
  39. response = requests.post(url, headers=self.headers, data=data, verify=False)
  40. if response.status_code == 200:
  41. result = response.json()
  42. if result['code'] == 0:
  43. # 返回温湿度
  44. return result['data']['condition']['temp'], result['data']['condition']['humidity']
  45. return None, None