Passed
Push — 2.x ( 9d19e6...fc10c4 )
by Jordi
05:50
created

senaite.core.browser.attachment.resolve_attachment   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 33
dl 0
loc 49
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A ResolveAttachmentView.download() 0 11 1
A ResolveAttachmentView.__init__() 0 3 1
A ResolveAttachmentView.__call__() 0 7 2
A ResolveAttachmentView.get_attachment_info() 0 10 1
1
# -*- coding: utf-8 -*-
2
3
from bika.lims import api
4
from Products.Five.browser import BrowserView
5
from senaite.core import logger
6
7
8
class ResolveAttachmentView(BrowserView):
9
    """Resolve Attachment by UID
10
11
    This view is used for attachment image links to attachments
12
    """
13
14
    def __init__(self, context, request):
15
        self.context = context
16
        self.request = request
17
18
    def __call__(self):
19
        uid = self.request.get("uid")
20
        attachment = api.get_object_by_uid(uid, default=None)
21
        if attachment is None:
22
            logger.error("No attachment found for UID: '{}'".format(uid))
23
            return
24
        return self.download(attachment)
25
26
    def get_attachment_info(self, attachment):
27
        """Returns a dictionary of attachment information
28
        """
29
        blob = attachment.getAttachmentFile()
30
31
        return {
32
            "data": blob.data,
33
            "content_type": blob.content_type,
34
            "filename": blob.filename,
35
            "last_modified": api.get_modification_date(attachment),
36
        }
37
38
    def download(self, attachment):
39
        info = self.get_attachment_info(attachment)
40
        data = info.get("data", "")
41
        content_type = info.get("content_type", "application/octet-stream")
42
        last_modified = info.get("last_modified")
43
        response = self.request.response
44
        set_header = response.setHeader
45
        set_header("Content-Type", "{}".format(content_type))
46
        set_header("Content-Length", len(data))
47
        set_header("Last-Modified", last_modified)
48
        response.write(data)
49