Skip to content

Instantly share code, notes, and snippets.

@aek
Last active March 27, 2018 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aek/3be60e8321fa05f88ea308fe91054991 to your computer and use it in GitHub Desktop.
Save aek/3be60e8321fa05f88ea308fe91054991 to your computer and use it in GitHub Desktop.
attachment controller to stream the download of attachment files
import base64
import logging
import werkzeug.utils
import werkzeug.wrappers
import hashlib
import mimetypes
import os
import re
import werkzeug
import werkzeug.exceptions
import werkzeug.routing
import werkzeug.urls
import werkzeug.utils
from odoo import api, http, models, tools, SUPERUSER_ID
from odoo.exceptions import AccessDenied, AccessError
from odoo.http import request, STATIC_CACHE, content_disposition, Controller
from odoo.modules.module import get_resource_path, get_module_path
_logger = logging.getLogger(__name__)
class BinaryStream(Controller):
def binary_content(self, xmlid=None, model='ir.attachment', id=None, field='datas', unique=False, filename=None, filename_field='datas_fname', download=False, mimetype=None, default_mimetype='application/octet-stream', env=None):
""" Get file, attachment or downloadable content
If the ``xmlid`` and ``id`` parameter is omitted, fetches the default value for the
binary field (via ``default_get``), otherwise fetches the field for
that precise record.
:param str xmlid: xmlid of the record
:param str model: name of the model to fetch the binary from
:param int id: id of the record from which to fetch the binary
:param str field: binary field
:param bool unique: add a max-age for the cache control
:param str filename: choose a filename
:param str filename_field: if not create an filename with model-id-field
:param bool download: apply headers to download the file
:param str mimetype: mintype of the field (for headers)
:param str default_mimetype: default mintype if no mintype found
:param Environment env: by default use request.env
:returns: (status, headers, content)
"""
env = env or request.env
# get object and content
obj = None
if xmlid:
obj = env.ref(xmlid, False)
elif id and model in env.registry:
obj = env[model].browse(int(id))
# obj exists
if not obj or not obj.exists() or field not in obj:
return (404, [], None)
# check read access
try:
last_update = obj['__last_update']
except AccessError:
return (403, [], None)
status, headers, content = None, [], None
# attachment by url check
module_resource_path = None
if model == 'ir.attachment' and obj.type == 'url' and obj.url:
url_match = re.match("^/(\w+)/(.+)$", obj.url)
if url_match:
module = url_match.group(1)
module_path = get_module_path(module)
module_resource_path = get_resource_path(module, url_match.group(2))
if module_path and module_resource_path:
module_path = os.path.join(os.path.normpath(module_path), '') # join ensures the path ends with '/'
module_resource_path = os.path.normpath(module_resource_path)
if module_resource_path.startswith(module_path):
content = open(module_resource_path, 'rb')
last_update = str(os.path.getmtime(module_resource_path))
if not module_resource_path:
module_resource_path = obj.url
if not content:
status = 301
content = module_resource_path
elif model == 'ir.attachment' and obj.type != 'url':
full_path = env['ir.attachment']._full_path(obj['store_fname'])
content = open(full_path, 'rb')
else:
content = obj[field] or ''
# filename
if not filename:
if filename_field in obj:
filename = obj[filename_field]
elif module_resource_path:
filename = os.path.basename(module_resource_path)
else:
filename = "%s-%s-%s" % (obj._name, obj.id, field)
# mimetype
mimetype = 'mimetype' in obj and obj.mimetype or False
if not mimetype:
if filename:
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype and getattr(env[model]._fields[field], 'attachment', False):
# for binary fields, fetch the ir_attachement for mimetype check
attach_mimetype = env['ir.attachment'].search_read(domain=[('res_model', '=', model), ('res_id', '=', id), ('res_field', '=', field)], fields=['mimetype'], limit=1)
mimetype = attach_mimetype and attach_mimetype[0]['mimetype']
headers += [('Content-Type', mimetype), ('X-Content-Type-Options', 'nosniff')]
# cache
# etag = hasattr(request, 'httprequest') and request.httprequest.headers.get('If-None-Match')
# retag = '"%s"' % hashlib.md5(last_update).hexdigest()
# status = status or (304 if etag == retag else 200)
status = 200
# headers.append(('ETag', retag))
# headers.append(('Cache-Control', 'max-age=%s' % (STATIC_CACHE if unique else 0)))
# content-disposition default name
if download:
headers.append(('Content-Disposition', env['ir.http'].content_disposition(filename)))
return (status, headers, content)
@http.route(['/web/content/stream',
'/web/content/stream/<string:xmlid>',
'/web/content/stream/<string:xmlid>/<string:filename>',
'/web/content/stream/<int:id>',
'/web/content/stream/<int:id>/<string:filename>',
'/web/content/stream/<int:id>-<string:unique>',
'/web/content/stream/<int:id>-<string:unique>/<string:filename>',
'/web/content/stream/<string:model>/<int:id>/<string:field>',
'/web/content/stream/<string:model>/<int:id>/<string:field>/<string:filename>'], type='http', auth="public")
def content_stream(self, xmlid=None, model='ir.attachment', id=None, field='datas', filename=None, filename_field='datas_fname', unique=None, mimetype=None, download=None, data=None, token=None):
status, headers, data_stream = self.binary_content(xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename, filename_field=filename_field, download=download, mimetype=mimetype)
if status == 304:
response = werkzeug.wrappers.Response(status=status, headers=headers)
elif status == 301:
return werkzeug.utils.redirect(data_stream, code=301)
elif status != 200:
response = request.not_found()
else:
response = werkzeug.wrappers.Response(data_stream, headers=headers, direct_passthrough=True)
if token:
response.set_cookie('fileToken', token)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment