You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Odoo 11中展示外部信息?求天气应用集成实现指南

Odoo 11 天气应用集成指南(附代码示例)

嘿,恭喜你已经搞定了OpenWeatherMap API的Python脚本!接下来咱们一步步把它集成到Odoo 11里,覆盖模型定义、视图展示(表单/树状/看板)全流程,直接上干货:

一、先搭好Odoo模块基础结构

首先创建一个名为weather_app的模块,结构如下:

weather_app/
├── __init__.py
├── __manifest__.py
├── models/
│   ├── __init__.py
│   └── weather.py
└── views/
    ├── weather_views.xml
    └── menu_views.xml

二、定义天气数据模型

在models/weather.py里,咱们要把API调用逻辑整合到Odoo模型中,同时定义存储天气数据的字段:

from odoo import models, fields, api
import requests

class WeatherRecord(models.Model):
    _name = 'weather.record'
    _description = 'Weather Record'

    city_name = fields.Char(string='City Name', required=True)
    temperature = fields.Float(string='Temperature (°C)')
    humidity = fields.Integer(string='Humidity (%)')
    weather_description = fields.Char(string='Weather Description')
    last_updated = fields.Datetime(string='Last Updated')

    @api.multi
    def action_fetch_weather(self):
        # 建议把API密钥放到Odoo系统参数里,不要硬编码!
        api_key = self.env['ir.config_parameter'].sudo().get_param('weather_app.api_key')
        base_url = "https://api.openweathermap.org/data/2.5/weather"
        
        for record in self:
            try:
                params = {
                    'q': record.city_name,
                    'appid': api_key,
                    'units': 'metric'  # 切换为摄氏度单位
                }
                response = requests.get(base_url, params=params)
                response.raise_for_status()
                data = response.json()

                # 更新天气字段
                record.write({
                    'temperature': data['main']['temp'],
                    'humidity': data['main']['humidity'],
                    'weather_description': data['weather'][0]['description'].title(),
                    'last_updated': fields.Datetime.now()
                })
            except Exception as e:
                raise models.ValidationError(f"获取天气失败: {str(e)}")

别忘了在models/__init__.py里导入这个模型:

from . import weather

三、配置模块清单(manifest.py)

指定模块依赖、视图文件等核心信息:

{
    'name': 'Weather Application',
    'version': '1.0',
    'author': 'Your Name',
    'category': 'Tools',
    'depends': ['base'],
    'data': [
        'views/menu_views.xml',
        'views/weather_views.xml',
    ],
    'installable': True,
    'auto_install': False,
}

四、创建视图(表单/树状/看板)

在views/weather_views.xml里定义三种视图:

1. 表单视图(展示详细天气信息)

<odoo>
    <record id="weather_record_form_view" model="ir.ui.view">
        <field name="name">weather.record.form.view</field>
        <field name="model">weather.record</field>
        <field name="arch" type="xml">
            <form string="Weather Record">
                <sheet>
                    <group>
                        <field name="city_name"/>
                        <button name="action_fetch_weather" type="object" string="Fetch Weather" class="btn-primary"/>
                    </group>
                    <separator string="Weather Details"/>
                    <group>
                        <field name="temperature" readonly="1"/>
                        <field name="humidity" readonly="1"/>
                        <field name="weather_description" readonly="1"/>
                        <field name="last_updated" readonly="1"/>
                    </group>
                </sheet>
            </form>
        </field>
    </record>

2. 树状视图(列表展示所有记录)

<record id="weather_record_tree_view" model="ir.ui.view">
        <field name="name">weather.record.tree.view</field>
        <field name="model">weather.record</field>
        <field name="arch" type="xml">
            <tree string="Weather Records">
                <field name="city_name"/>
                <field name="temperature"/>
                <field name="humidity"/>
                <field name="weather_description"/>
                <field name="last_updated"/>
            </tree>
        </field>
    </record>

3. 看板视图(卡片式展示关键信息)

<record id="weather_record_kanban_view" model="ir.ui.view">
        <field name="name">weather.record.kanban.view</field>
        <field name="model">weather.record</field>
        <field name="arch" type="xml">
            <kanban string="Weather Kanban">
                <field name="city_name"/>
                <field name="temperature"/>
                <field name="humidity"/>
                <field name="weather_description"/>
                <templates>
                    <t t-name="kanban-box">
                        <div class="oe_kanban_global_click">
                            <div class="oe_kanban_content">
                                <h3><field name="city_name"/></h3>
                                <div class="oe_kanban_details">
                                    <p>Temp: <field name="temperature"/> °C</p>
                                    <p>Humidity: <field name="humidity"/> %</p>
                                    <p><field name="weather_description"/></p>
                                    <p class="text-muted">Updated: <field name="last_updated"/></p>
                                </div>
                            </div>
                        </div>
                    </t>
                </templates>
            </kanban>
        </field>
    </record>
</odoo>

最后添加动作和菜单

在views/menu_views.xml里配置系统菜单入口:

<odoo>
    <record id="action_weather_record" model="ir.actions.act_window">
        <field name="name">Weather Records</field>
        <field name="res_model">weather.record</field>
        <field name="view_mode">tree,form,kanban</field>
    </record>

    <menuitem name="Weather App" id="menu_weather_root" sequence="10"/>
    <menuitem name="Weather Records" id="menu_weather_records" parent="menu_weather_root" action="action_weather_record"/>
</odoo>

五、关键注意事项

  • API密钥管理:别把API密钥硬编码在代码里,建议通过Settings > Technical > System Parameters添加weather_app.api_key参数,这样更安全也方便修改。
  • 异常处理:代码里已经加了基本的异常捕获,你可以根据需求扩展(比如处理城市名称不存在、网络超时等情况)。
  • 定时刷新:如果需要自动更新天气,可以用Odoo的ir.cron定时任务,定期调用action_fetch_weather方法。

六、测试模块

  1. 把模块放到Odoo的addons目录下
  2. 刷新模块列表,找到Weather Application并安装
  3. 打开菜单Weather App > Weather Records,创建城市记录,点击Fetch Weather按钮测试API调用和视图展示

内容的提问来源于stack exchange,提问作者M.Lamine Lalmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:57:05