weather forecast

This commit is contained in:
XuanHuyen
2025-04-16 10:07:51 +07:00
parent 2fb1ecffc2
commit 1adc5cc52a
13 changed files with 423 additions and 0 deletions
+192
View File
@@ -0,0 +1,192 @@
from odoo import fields, models, api, _
from odoo.exceptions import UserError
import requests
from collections import defaultdict
from datetime import datetime
class WeatherAPI(models.Model):
_name = 'weather.api'
_description = 'Weather API'
_rec_name = 'company_id'
company_id = fields.Many2one('res.company', string='Công ty', required=True, default=lambda self: self.env.company)
current_temperature = fields.Float(string="Nhiệt độ hiện tại", compute="_compute_weather", store=False)
current_humidity = fields.Float(string="Độ ẩm hiện tại", compute="_compute_weather", store=False)
current_wind_speed = fields.Float(string="Gió hiện tại", compute="_compute_weather", store=False)
current_description = fields.Char(string="Tình trạng thời tiết", compute="_compute_weather", store=False)
today_hourly_first = fields.Html(string="1h - 8h", compute="_compute_weather", store=False)
today_hourly_second = fields.Html(string="9h - 16h", compute="_compute_weather", store=False)
today_hourly_third = fields.Html(string="17h - 24h", compute="_compute_weather", store=False)
next_3_days_weather = fields.Html(string="Dự báo 3 ngày", compute="_compute_weather", store=False)
@api.depends()
def _compute_weather(self):
for rec in self:
current = rec.get_weather_current()
rec.current_temperature = current.get('temperature')
rec.current_humidity = current.get('humidity')
rec.current_wind_speed = current.get('wind_speed')
rec.current_description = current.get('description')
# Weather by time blocks
today = rec._get_today_weather()
rec.today_hourly_first = rec._format_html(today['first'])
rec.today_hourly_second = rec._format_html(today['second'])
rec.today_hourly_third = rec._format_html(today['third'])
# Next 3 days
forecast = rec._get_next_3days_forecast()
html = "<ul>"
for day in forecast:
html += f"<li><b>{day['date']}</b>: {day['main_description']}, {day['temp_min']}°C - {day['temp_max']}°C, Gió: {day['wind_speed']} m/s</li>"
html += "</ul>"
rec.next_3_days_weather = html
def _format_html(self, data):
if not data:
return "<p>Không có dữ liệu.</p>"
html = "<ul>"
for d in data:
html += f"<li><b>{d['hour']}h</b>: {d['description']}, {d['temp_min']}°C - {d['temp_max']}°C, Gió: {d['wind_speed']} m/s</li>"
html += "</ul>"
return html
# Lấy thông tin API key từ cấu hình
@api.model
def get_api_key(self):
"""Lấy thông tin API key từ cấu hình"""
api_key = self.env['ir.config_parameter'].sudo().get_param('weather_infor.api_key')
if not api_key:
raise UserError("API Key chưa được cấu hình. Vui lòng vào Settings > Weather API Settings để nhập API Key.")
return api_key
# Lấy thông tin thành phố từ cấu hình công ty
@api.model
def get_city(self):
"""Lấy thông tin thành phố từ cấu hình công ty"""
city = self.env.company.city
if not city:
raise UserError(_("Thành phố chưa được cấu hình. Vui lòng vào Settings > Công ty để nhập thành phố."))
return city
# Lấy thông tin thời tiết hiện tại
@api.model
def get_weather_current(self):
"""Lấy dữ liệu thời tiết hiện tại"""
api_key = self.get_api_key()
city = self.get_city()
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return {
'temperature': data['main']['temp'],
'humidity': data['main']['humidity'],
'wind_speed': data['wind']['speed'],
'description': data['weather'][0]['description']
}
else:
raise UserError(_("Không thể lấy dữ liệu thời tiết. Vui lòng kiểm tra lại API key hoặc tên thành phố."))
# Lấy thông tin thời tiết 3 ngày
@api.model
def _get_next_3days_forecast(self):
"""Lấy dữ liệu thời tiết cho 3 ngày tiếp theo"""
api_key = self.get_api_key()
city = self.get_city()
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code != 200:
raise UserError(_("Không thể lấy dữ liệu thời tiết. Vui lòng kiểm tra lại API key hoặc tên thành phố."))
data = response.json()
forecast_data = data['list']
# Gom dữ liệu theo ngày
weather_data = defaultdict(list)
for forecast in forecast_data:
dt_txt = forecast['dt_txt']
date_str = dt_txt.split(' ')[0]
weather_data[date_str].append(forecast)
# Chọn 3 ngày tiếp theo
sorted_dates = sorted(weather_data.keys())
today = datetime.now().date()
if today in sorted_dates:
sorted_dates.remove(today)
next_3_days = sorted_dates[1:4]
result = []
for date in next_3_days:
daily_forecasts = weather_data[date]
temps = [f['main']['temp'] for f in daily_forecasts]
humidities = [f['main']['humidity'] for f in daily_forecasts]
descriptions = [f['weather'][0]['description'] for f in daily_forecasts]
wind_speeds = [f['wind']['speed'] for f in daily_forecasts]
result.append({
'date': date,
'temp_min': min(temps),
'temp_max': max(temps),
'humidity': round(sum(humidities) / len(humidities), 2),
'wind_speed': round(sum(wind_speeds) / len(wind_speeds), 2),
'main_description': max(set(descriptions), key=descriptions.count), # mô tả xuất hiện nhiều nhất
})
return result
# Lấy thông tin thời tiết ngày hôm nay, chia làm 3 khung giờ
@api.model
def _get_today_weather(self):
"""Lấy dữ liệu thời tiết ngày hôm nay chia làm 3 khung giờ: 1-8h, 9-16h, 17-24h"""
api_key = self.get_api_key()
city = self.env.company.city
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code != 200:
raise UserError(_("Không thể lấy dữ liệu thời tiết. Vui lòng kiểm tra lại API key hoặc tên thành phố."))
data = response.json()
forecast_data = data['list']
today_str = datetime.now().strftime('%Y-%m-%d')
hourly_data = {
'first': [], # 1-8h
'second': [], # 9-16h
'third': [] # 17-24h
}
for forecast in forecast_data:
dt_txt = forecast['dt_txt']
date_part, time_part = dt_txt.split(' ')
if date_part != today_str:
continue # chỉ lấy dữ liệu của ngày hôm nay
hour = int(time_part.split(':')[0])
weather_info = {
'hour': hour,
'date': date_part,
'temp_min': forecast['main']['temp_min'],
'temp_max': forecast['main']['temp_max'],
'humidity': forecast['main']['humidity'],
'wind_speed': forecast['wind']['speed'],
'description': forecast['weather'][0]['description']
}
if 0 <= hour <= 8:
hourly_data['first'].append(weather_info)
elif 9 <= hour <= 16:
hourly_data['second'].append(weather_info)
else:
hourly_data['third'].append(weather_info)
return hourly_data