iT邦幫忙

2024 iThome 鐵人賽

DAY 17
0
Odoo

前後端整合學習,不只是後端管理系列 第 17

【Day17】 odoo 資料庫串接(三) PUT

  • 分享至 

  • xImage
  •  

1. PUT 請求:更新維修訂單

我們將添加一個 PUT 路由,用於更新維修訂單。

Controller 內容(PUT 請求):

from odoo import http
from odoo.http import request
import json

class RepairOrderController(http.Controller):

    # PUT 請求:更新維修訂單
    @http.route('/repair/orders/<int:order_id>', type='json', auth='public', methods=['PUT'], csrf=False)
    def update_repair_order(self, order_id):
        try:
            # 獲取 JSON 數據
            data = request.jsonrequest

            # 查找訂單
            repair_order = request.env['repair.order'].sudo().browse(order_id)

            if not repair_order.exists():
                return http.Response(
                    json.dumps({'status': 'error', 'message': 'Order not found'}),
                    content_type='application/json'
                )

            # 更新維修訂單
            repair_order.sudo().write({
                'name': data.get('name', repair_order.name),
                'product_id': data.get('product_id', repair_order.product_id.id),
                'partner_id': data.get('partner_id', repair_order.partner_id.id),
                'state': data.get('state', repair_order.state),
            })

            return http.Response(
                json.dumps({
                    'status': 'success',
                    'message': 'Repair order updated successfully',
                    'order_id': order_id
                }),
                content_type='application/json'
            )

        except Exception as e:
            return http.Response(
                json.dumps({'status': 'error', 'message': str(e)}),
                content_type='application/json'
            )

Postman 請求格式(PUT):

  • 方法PUT
  • URLhttp://localhost:8069/repair/orders/<order_id>(例如 http://localhost:8069/repair/orders/1
  • Headers
    • Content-Type: application/json
  • Body
    • 選擇 raw 並設置為 JSON 格式
    • 更新的數據:
{
  "name": "Updated Repair Order Name",
  "product_id": 2,
  "partner_id": 3,
  "state": "confirmed"
}

測試指南:

PUT 請求:

  1. 使用 Postman 發送 PUT 請求來更新維修訂單的數據。
  2. 將請求的 URL 設置為 http://localhost:8069/repair/orders/<order_id>,並將 order_id 替換為具體的維修訂單 ID。
  3. 在 Body 中放入更新的數據。

回應格式:

  • 成功的 PUT 請求應返回:
{
  "status": "success",
  "message": "Repair order updated successfully",
  "order_id": 1
}

上一篇
【Day16】 odoo 資料庫串接(三) POST
下一篇
【Day18】 odoo 資料庫串接(三) DELETE
系列文
前後端整合學習,不只是後端管理19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言