[ADD] website ir_http: serve binary ir.attchments with urls
authorFabien Meghazi <fme@openerp.com>
Mon, 24 Mar 2014 15:17:28 +0000 (16:17 +0100)
committerFabien Meghazi <fme@openerp.com>
Mon, 24 Mar 2014 15:17:28 +0000 (16:17 +0100)
bzr revid: fme@openerp.com-20140324151728-hpegewvf3b38ndyi

addons/website/models/ir_http.py

index 47c0853..a7c0661 100644 (file)
@@ -1,8 +1,10 @@
 # -*- coding: utf-8 -*-
+import datetime
+import hashlib
 import logging
+import mimetypes
 import re
 import traceback
-
 import werkzeug
 import werkzeug.routing
 
@@ -94,9 +96,40 @@ class ir_http(orm.AbstractModel):
         if path != request.httprequest.path:
             return werkzeug.utils.redirect(path)
 
+    def _serve_attachment(self):
+        domain = [('type', '=', 'binary'), ('url', '=', request.httprequest.path)]
+        attach = self.pool['ir.attachment'].search_read(request.cr, request.uid, domain, ['__last_update', 'datas', 'datas_fname'], context=request.context)
+        if attach:
+            wdate = attach[0]['__last_update']
+            datas = attach[0]['datas']
+            fname = attach[0]['datas_fname']
+            response = werkzeug.wrappers.Response()
+            server_format = openerp.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT
+            try:
+                response.last_modified = datetime.datetime.strptime(wdate, server_format + '.%f')
+            except ValueError:
+                # just in case we have a timestamp without microseconds
+                response.last_modified = datetime.datetime.strptime(wdate, server_format)
+
+            response.set_etag(hashlib.sha1(datas).hexdigest())
+            response.make_conditional(request.httprequest)
+
+            if response.status_code == 304:
+                return response
+
+            guessed_mimetype = mimetypes.guess_type(fname)
+            response.mimetype = guessed_mimetype[0] or 'application/octet-stream'
+            response.set_data(datas.decode('base64'))
+            return response
+
     def _handle_exception(self, exception=None, code=500):
         if isinstance(exception, werkzeug.exceptions.HTTPException) and hasattr(exception, 'response') and exception.response:
             return exception.response
+
+        attach = self._serve_attachment()
+        if attach:
+            return attach
+
         if getattr(request, 'website_enabled', False) and request.website:
             values = dict(
                 exception=exception,