odoo16--controller层文件/图片上传接口、分页操作、数据日期筛选
用户上传照片文件至服务器,并返回前端照片存储位置
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”,并传入起始日期与终止日期
本篇主要分享了一些接口的基础数据调用用法方法