资讯专栏INFORMATION COLUMN

odoo打包下载

JohnLui / 1801人阅读

摘要:视图中下载按钮的编辑附件打包下载中获取需要下载的文件的,并返回字符串集合打包下载的方法中的打包下载引用和方法,如下代码

view 视图中下载按钮的编辑
    
        附件打包下载
        
        
        code
        
            if records:
                action = {
                    "name": "Visit Webpage",
                    "type": "ir.actions.act_url",
                    "url": "/document/zip/"+str(records.download_zip()),
                    "target": "self",
                }
        
    
model 中获取需要下载的文件的ID,并返回字符串集合 打包下载的方法
@api.multi
def download_zip(self):
    dones = self.env["ir.attachment"].search([("res_model", "=", "activity.event"), ("res_id", "=", self.id)])
    file_ids = ""
    for x in dones:
        file_ids = file_ids + str(x.id) + ","
    print(file_ids)
    return {
        file_ids
    }
controller.py中的打包下载引用和方法,如下代码
# -*- coding: utf-8 -*-
import base64
import io
import jinja2
import json
import logging
import os
import sys
import zipfile
import time

import werkzeug
import werkzeug.exceptions
import werkzeug.utils
import werkzeug.wrappers
import werkzeug.wsgi
from odoo import http
from odoo.http import content_disposition, dispatch_rpc, request, 
    serialize_exception as _serialize_exception, Response
from odoo.exceptions import AccessError, UserError, AccessDenied
from odoo.models import check_method_name
from odoo.service import db, security

_logger = logging.getLogger(__name__)

if hasattr(sys, "frozen"):
    # When running on compiled windows binary, we don"t have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "views"))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader("odoo.addons.web", "views")

env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = json.dumps

# 1 week cache for asset bundles as advised by Google Page Speed
BUNDLE_MAXAGE = 60 * 60 * 24 * 7

DBNAME_PATTERN = "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$"

#----------------------------------------------------------
# Odoo Web helpers
#----------------------------------------------------------

db_list = http.db_list

db_monodb = http.db_monodb

class DownloadAll(http.Controller):

    def _get_file_response(self, id, filename=None, field="datas", share_id=None, share_token=None):
        """
        returns the http response to download one file.

        """
        status, headers, content = request.registry["ir.http"].binary_content(
            id=id, field=field, filename=filename, related_id=share_id,
            access_token=share_token, access_mode="documents_share", download=True)

        if status == 304:
            response = werkzeug.wrappers.Response(status=status, headers=headers)
        elif status == 301:
            return werkzeug.utils.redirect(content, code=301)
        elif status != 200:
            response = request.not_found()
        else:
            content_base64 = base64.b64decode(content)
            headers.append(("Content-Length", len(content_base64)))
            response = request.make_response(content_base64, headers)

        return response

    def _make_zip(self, name, attachments):
        """returns zip files for the Document Inspector and the portal.

        :param name: the name to give to the zip file.
        :param attachments: files (ir.attachment) to be zipped.
        :return: a http response to download a zip file.
        """
        stream = io.BytesIO()
        try:
            with zipfile.ZipFile(stream, "w") as doc_zip:
                for attachment in attachments:
                    if attachment.type in ["url", "empty"]:
                        continue
                    filename = attachment.datas_fname
                    doc_zip.writestr(filename, base64.b64decode(attachment["datas"]),
                                     compress_type=zipfile.ZIP_DEFLATED)
        except zipfile.BadZipfile:
            _logger.exception("BadZipfile exception")

        content = stream.getvalue()
        headers = [
            ("Content-Type", "zip"),
            ("X-Content-Type-Options", "nosniff"),
            ("Content-Length", len(content)),
            ("Content-Disposition", content_disposition(name))
        ]
        return request.make_response(content, headers)

    @http.route(["/document/zip/"], type="http", auth="public")
    def _get_zip(self, file_ids=None, *args, **kwargs):
        """route to get the zip file of the selection in the document"s Kanban view (Document inspector).
        :param file_ids: if of the files to zip.
        :param zip_name: name of the zip file.
        """
        file_ids = file_ids[2:-3]
        print(file_ids)
        timestamp = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
        zip_name = "activity-" + timestamp + ".zip"
        ids_list = [int(x) for x in file_ids.split(",")]
        print(ids_list)
        env = request.env
        return self._make_zip(zip_name, env["ir.attachment"].browse(ids_list))

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43329.html

相关文章

  • Odoo 中添加自定义页面

    摘要:一般情况下都是在中继承后在其末尾添加相关资源路径除了资源需要引入外,我们编写的页面模板也许要引入,打开并在底部添加我们的自定义页面文件大功告成,一个最简单的自定义页面已经完成了,安装模块然后运行看看效果吧。 前些天群里的小伙伴问了些关于在 Odoo 管理后台自定义页面和 Widget 的问题,那我就来写一篇简短的内容,教大家如何创建自定义页面并引用第三方库。如果大家有看我之前写的基础教...

    Jackwoo 评论0 收藏0
  • Odoo 基础教程系列」第一篇——环境准备

    摘要:安装好后,在中执行查看版本信息,应该会看到输出如下信息版本号可能会不同如果提示未找到,则需要手动将用户基础目录下的添加到中。相关文章基础教程系列第篇开天坑啦 showImg(https://segmentfault.com/img/bV4GZu?w=1262&h=911); 之前说好的 「Odoo 基础教程系列」终于来了(撒花)~刚过完年重新投入到工作中,一下子事情有点多都要忙不过来了...

    szysky 评论0 收藏0
  • Odoo 中生成唯一不重复的序列号

    摘要:最近在做的项目中有一个需求是要让某个字段值根据记录产生的日期和一定的组合规则按顺序生成一个序列号,这个序列号不可重复,这原本是一个很常见的需求,没有多想就写好了。 showImg(https://segmentfault.com/img/remote/1460000013229918?w=1000&h=667); 最近在做的项目中有一个需求是要让某个字段值根据记录产生的日期和一定的组合...

    wujl596 评论0 收藏0
  • Odoo 基础教程系列」第二篇——从 Todo 应用开始(1)

    摘要:虽然这是个很简单的应用,但是希望大家可以动手一起操作,从最简单的开始上手学习如何使用这个框架。则是在和之间,负责响应用户操作,从中获取数据进行处理并返回到中。 showImg(https://segmentfault.com/img/bV66tE?w=728&h=410); 在第一篇教程发布之后差不多一个月的今天,终于完成了第二篇内容,这个发布周期拖得实在是有点太长了,我都觉得不好意思...

    UCloud 评论0 收藏0
  • 抢滩中小企业云市场卡位战,SAP 、Odoo等国外巨头谁能胜出

    摘要:年月日,在中国新年前夕,发布了中国加速计划,计划在未来五年,持续加大对中国中小企业市场的投入。一向以高端市场为傲的成为中国中小企业市场的闯局者。2019年1月31日,在中国新年前夕,SAP发布了中国加速计划,计划在未来五年,持续加大对中国中小企业市场的投入。一向以高端市场为傲的SAP成为中国中小企业市场的闯局者。无独有偶。Oracle此前的定位主要是企业级高端市场,但云计算给Oracle进入...

    MorePainMoreGain 评论0 收藏0

发表评论

0条评论

JohnLui

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<