weather.py 1.2 KB

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