main.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import base64
  2. import psycopg2
  3. import functools
  4. import openerp
  5. from openerp import SUPERUSER_ID
  6. from openerp import http
  7. from openerp.http import request
  8. from openerp.addons.web.controllers.main import content_disposition
  9. from openerp.addons.mail.controllers.main import MailController
  10. from openerp.addons.web.controllers.main import Binary
  11. import mimetypes
  12. import logging
  13. from openerp.http import request, serialize_exception as _serialize_exception
  14. _logger = logging.getLogger(__name__)
  15. def serialize_exception(f):
  16. @functools.wraps(f)
  17. def wrap(*args, **kwargs):
  18. try:
  19. return f(*args, **kwargs)
  20. except Exception, e:
  21. _logger.exception("An exception occured during an http request")
  22. se = _serialize_exception(e)
  23. error = {
  24. 'code': 200,
  25. 'message': "Odoo Server Error",
  26. 'data': se
  27. }
  28. return werkzeug.exceptions.InternalServerError(simplejson.dumps(error))
  29. return wrap
  30. class MyMailController(MailController):
  31. _cp_path = '/mail'
  32. @http.route('/mail/download_attachment', type='http', auth='user')
  33. def download_attachment(self, model, id, method, attachment_id, **kw):
  34. result = super(MyMailController, self).download_attachment(model, id, method, attachment_id, **kw)
  35. result.headers['Content-Disposition'] = result.headers['Content-Disposition'].replace('attachment', 'inline')
  36. return result
  37. class MyBinary(Binary):
  38. @http.route('/web/binary/saveas', type='http', auth="public")
  39. def saveas(self, model, field, id=None, filename_field=None, **kw):
  40. Model = request.registry[model]
  41. cr, uid, context = request.cr, request.uid, request.context
  42. fields = [field]
  43. if filename_field:
  44. fields.append(filename_field)
  45. if id:
  46. res = Model.read(cr, uid, [int(id)], fields, context)[0]
  47. else:
  48. res = Model.default_get(cr, uid, fields, context)
  49. filecontent = base64.b64decode(res.get(field) or '')
  50. if not filecontent:
  51. return request.not_found()
  52. else:
  53. content_type = ""
  54. filename = '%s_%s' % (model.replace('.', '_'), id)
  55. if filename_field:
  56. filename = res.get(filename_field, '') or filename
  57. content_type = mimetypes.guess_type(filename)
  58. return request.make_response(filecontent,
  59. headers=[('Content-Type', content_type[0] or 'application/octet-stream'),
  60. ('Content-Disposition', content_disposition(filename).replace('attachment', 'inline'))])