IPWeatherObject.py 2.3 KB

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