39 lines
1.7 KiB
Python
39 lines
1.7 KiB
Python
from odoo import fields, models, api, _
|
|
import requests
|
|
from odoo.exceptions import UserError
|
|
|
|
class WeatherInformation(models.Model):
|
|
_name = 'weather.information'
|
|
_description = 'Weather Information'
|
|
|
|
city = fields.Char(string='Thành phố', required=True)
|
|
temperature = fields.Float(string='Nhiệt độ (°C)', readonly=True)
|
|
humidity = fields.Float(string='Độ ẩm (%)', readonly=True)
|
|
wind_speed = fields.Float(string='Tốc độ gió', readonly=True)
|
|
description = fields.Char(string="Mô tả")
|
|
|
|
@api.model
|
|
def get_weather_information(self, city):
|
|
"""Fetch weather data from OpenWeatherMap API"""
|
|
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.")
|
|
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("Could not fetch weather data. Please check the city name or API Key.")
|
|
|
|
def fetch_weather(self):
|
|
"""Fetch weather data and update the record"""
|
|
for record in self:
|
|
weather_data = self.get_weather_information(record.city)
|
|
record.write(weather_data) |