weather.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # -*- coding: utf-8 -*-
  2. import json
  3. from httpx import AsyncClient, URL
  4. from app.core.config import settings
  5. from app.services.service import Service
  6. from app.utils.date import get_time_str
  7. class WeatherService(Service):
  8. def __init__(self, client: AsyncClient, server_settings=settings):
  9. super(WeatherService, self).__init__(client)
  10. self._base_url = URL(server_settings.WEATHER_HOST)
  11. self._now_time = get_time_str(fmt="YYYY-MM-DD HH:mm:ss")
  12. async def get_realtime_weather(self, project_id: str) -> dict:
  13. url = self._base_url.join(
  14. "EMS_Weather/Spring/MVC/entrance/unifier/HourHistoryData"
  15. )
  16. headers = {
  17. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  18. "Connection": "close",
  19. }
  20. params = {
  21. "projectId": project_id,
  22. "startTime": get_time_str(
  23. 60 * 60 * 2, flag="ago", fmt="YYYY-MM-DD HH:mm:ss"
  24. ),
  25. "endTime": self._now_time,
  26. }
  27. raw_info = await self._post(
  28. url, params={"jsonString": json.dumps(params)}, headers=headers
  29. )
  30. try:
  31. result = raw_info.get("content")[-1]
  32. except (KeyError, TypeError, IndexError):
  33. result = {}
  34. return result