odoo16--controller层编写文件/图片上传接口、分页操作、数据日期筛选

该文章展示了在Odoo16中如何实现控制器层的文件和图片上传接口,以及如何进行分页操作和根据日期筛选数据。用户可以上传照片和文件到服务器,并获取存储位置。同时,接口支持按需展示数据,如按今日、昨日、本周、本月等条件筛选猫猫信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用户上传照片文件至服务器,并返回前端照片存储位置

from odoo import models,fields,api
from odoo.exceptions import UserError,ValidationError

class MyCatHomePage(models.Model):
    _name = "my.cats"
    _description = 'My Cats Homepage'
    
 	cat_image = fields.Binary(string='猫猫图片')
import urllib.parse

# 上传照片接口
    '''
    file      照片
    uid       猫猫id
    '''

    @http.route('/CatPhotoUploadfile', type='http', methods=['POST'], auth="public", csrf=False, cors='*')
    def CatPhotoUploadfile(self, **kw):
    	#将用户传来的有效负载存储到变量file中
        file = request.httprequest.data
        #打印一条信息,其中包含了文件在服务器上的路径和名称,以记录活动图像的请求。
        _logger.info("-----------/fmcg/active/image--------------------------:%s", kw['file'])
        if not kw['file']:
            return json.dumps({'result': 'success', 'message': 'no image'})
        #将文件数据编码为base64字符串格式
        base64_data = base64.b64encode(kw['file'].read())
        user_obj = request.env['my.cats'].sudo()
        user_id = user_obj.search([('id', '=', kw['uid'])], limit=1)
        if not user_id:
            return json.dumps({'result': 'fail', 'message': 'not find record'})
        #'ir.attachment'是odoo统一存附件的数据表
        #将文件数据写入存储附件的表中,并关联模型
        attachment = request.env['ir.attachment'].sudo().create({
            'name': kw['file'].filename,
            'datas': base64_data,
            'res_id': user_id.id,
            'res_model': 'my.cats',
        })
        #把文件信息写入猫猫信息数据表中存储图片的字段:cat_image
        user_id.write({'cat_image':attachment.datas})
        #格式化存储路径,并将此路径返回至前端,以调用图片展示
        attachment_url = '/web/content/%s/%s' % (
        attachment.id, urllib.parse.quote(attachment.name))
        return json.dumps({
                     'result': 'success', 
                     'message': 'success', 
                     'file_url':attachment_url})

用户上传文件至服务器,并返回前端文件存储位置

from odoo import models,fields,api
from odoo.exceptions import UserError,ValidationError

class MyCatHomePage(models.Model):
    _name = "my.cats"
    _description = 'My Cats Homepage'
    
 	cat_file = fields.Binary(string='猫猫档案')
import urllib.parse

    # 上传文件接口
    '''
    file      文件
    uid       猫猫id
    '''
    @http.route('/uploadFile', type='http', methods=['POST'], auth="public", csrf=False, cors='*')
    def uploadFile(self, **kw):
        file = request.httprequest.files.get('file')
        if not file:
            return json.dumps({'result': 'fail', 'message': '无提供文件'})

        # 生成文件名
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
        file_name = f'file_{timestamp}_{file.filename}'

        # 保存文件至服务器
        file_path = os.path.join('/root/zzz/web/project/my_cats', 'uploaded_files', file_name)
        file.save(file_path)

        # 将文件信息存储到数据库
        user_obj = request.env['my.cats'].sudo()
        user_id = user_obj.search([('id', '=', int(kw['uid']))])
        if not user_id:
            return json.dumps({'result': 'fail', 'message': '用户不存在'})

        attachment = request.env['ir.attachment'].sudo().create({
            'name': file_name,
            'datas': base64.b64encode(file.read()),
            'res_id': user_id.id,
            'res_model': 'my.cats',
        })
			
		user_id.write({'cat_file ':attachment.datas})
        attachment_url = '/web/content/%s/%s' % (
        attachment.id, urllib.parse.quote(attachment.name))

        return json.dumps({'result': 'success', 'message': 'File uploaded successfully', 'file_url':attachment_url})

对访问的接口设置分页,使得数据根据前端传来的页数与限制条目进行展示

		#...前面是你查询出来的结果
		#page若没有传参,则默认为1
    	page = int(request.params.get('page', 1))
    	#limit若没有传参,则默认为10
        limit = int(request.params.get('limit', 10))
        if page < 1:
            page = 1
        if limit < 1:
            limit = 10
        start = (page - 1) * limit
        end = page * limit
        data = result[start:end]
        data_count = len(result)
        return{
            "code": 1,
            "data": data,
            'data_count': data_count
        }
  • 不传入参数的情况下,将所有数据返回给前端
    在这里插入图片描述
  • 可以看到odoo社区页面一共是四条数据

在这里插入图片描述

  • 若我传入page:1 limit:2的数据,则每一页有两条数据,返回第一页
    在这里插入图片描述
  • 第二页返回后两条数据
    在这里插入图片描述

根据日期筛选数据

  • 假设我们需要实现原型设计如下:

  • 当用户点击今日、昨日、本周、本月或其他

在这里插入图片描述

from datetime import datetime,timedelta,date
		'''
    page 页数
    limit 显示条目
    type    1 -- 今日
            2 -- 昨日
            3 -- 本周
            4 -- 本月
            5 -- 传入时间
    start_date   开始日期
    end_date     结束日期
    '''
    @http.route('/getCatList', type='json', auth='none', cors='*', csrf=False)
    def getCatList(self, **kw):
        cat_obj = request.env['my.cats'].sudo()

        # 今日
        if kw['type'] == "1":
            today = date.today()
            cat_id = cat_obj.search([('doing_date', '=', today)]) 
        
        # 昨日
        elif kw['type'] == "2":
            today = date.today()
            yesterday = today - timedelta(days=1)
            cat_id = cat_obj.search([('doing_date', '=', yesterday)])

        # 本周
        elif kw['type'] == "3":
            today = date.today()
            start_of_week = today - timedelta(days=today.weekday())
            end_of_week = start_of_week + timedelta(days=6)
            cat_id = cat_obj.search([('doing_date', '>=', start_of_week), 
                                    ('doing_date', '<=', end_of_week)])
         
        # 本月
        elif kw['type'] == "4":
            today = date.today()
            start_of_month = date(today.year, today.month, 1)
            end_of_month = date(today.year, today.month+1, 1) - timedelta(days=1)
            cat_id = cat_obj.search([('doing_date', '>=', start_of_month), 
                                    ('doing_date', '<=', end_of_month)])
        
        # 传入具体日期
        elif kw['type'] == "5":
            start_date = datetime.strptime(kw['start_date'], '%Y-%m-%d')
            end_date = datetime.strptime(kw['end_date'], '%Y-%m-%d')
            cat_id = cat_obj.search([('doing_date', '>=', start_date), 
                                    ('doing_date', '<=', end_date)])
        else: 
            cat_id = cat_obj.search([])

        result=[]
        for cat in cat_id:
            result.append({
                'id':cat.id,
                'name':cat.name,
                'code':cat.code,
                'age':cat.age,
                'cat_type':cat.cat_type,
                'price':cat.price,
                'borrowed':cat.borrowed,
                'cats_home':cat.cats_home.name,
                'personality_id':cat.personality_id.name,
                'description':cat.description
            })
        page = int(request.params.get('page', 1))
        limit = int(request.params.get('limit', 10))
        if page < 1:
            page = 1
        if limit < 1:
            limit = 10
        start = (page - 1) * limit
        end = page * limit
        data = result[start:end]
        data_count = len(result)
        return{
            "code": 1,
            "data": data,
            'data_count': data_count
        }

  • 这里能看到我创建了四条猫猫数据,根据入店时间进行筛选

在这里插入图片描述

  • 筛选出入店时间为今日的猫猫数据:type:“1”

在这里插入图片描述

  • 筛选出入店时间分别为昨日、本周、本月的猫猫数据:type:“2”,type:“3”,type:“4”,

  • 这里不做赘述,需要注意的是,本月数据按照月份判定,如当前传入type:“4”,则返回三个猫猫信息:今日猫猫、昨日猫猫、本月猫猫;入店时间为 2023-06-01 – 2023-06-30

  • 筛选出入店时间为指定日期的猫猫数据:type:“5”,并传入起始日期与终止日期
    在这里插入图片描述本篇主要分享了一些接口的基础数据调用用法方法

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值