cubicweb/web/test/data/cubicweb_file/entities.py
changeset 12519 aff5d3498f68
child 12567 26744ad37953
equal deleted inserted replaced
12518:12e8b65146d9 12519:aff5d3498f68
       
     1 from six import text_type
       
     2 from logilab.mtconverter import guess_mimetype_and_encoding
       
     3 from cubicweb.entities import AnyEntity, fetch_config
       
     4 
       
     5 
       
     6 class File(AnyEntity):
       
     7     """customized class for File entities"""
       
     8     __regid__ = 'File'
       
     9     fetch_attrs, cw_fetch_order = fetch_config(['data_name', 'title'])
       
    10 
       
    11     def set_format_and_encoding(self):
       
    12         """try to set format and encoding according to known values (filename,
       
    13         file content, format, encoding).
       
    14 
       
    15         This method must be called in a before_[add|update]_entity hook else it
       
    16         won't have any effect.
       
    17         """
       
    18         assert 'data' in self.cw_edited, "missing mandatory attribute data"
       
    19         if self.cw_edited.get('data'):
       
    20             if (hasattr(self.data, 'filename')
       
    21                     and not self.cw_edited.get('data_name')):
       
    22                 self.cw_edited['data_name'] = self.data.filename
       
    23         else:
       
    24             self.cw_edited['data_format'] = None
       
    25             self.cw_edited['data_encoding'] = None
       
    26             self.cw_edited['data_name'] = None
       
    27             return
       
    28         if 'data_format' in self.cw_edited:
       
    29             format = self.cw_edited.get('data_format')
       
    30         else:
       
    31             format = None
       
    32         if 'data_encoding' in self.cw_edited:
       
    33             encoding = self.cw_edited.get('data_encoding')
       
    34         else:
       
    35             encoding = None
       
    36         if not (format and encoding):
       
    37             format, encoding = guess_mimetype_and_encoding(
       
    38                 data=self.cw_edited.get('data'),
       
    39                 # use get and not get_value since data has changed, we only
       
    40                 # want to consider explicitly specified values, not old ones
       
    41                 filename=self.cw_edited.get('data_name'),
       
    42                 format=format, encoding=encoding,
       
    43                 fallbackencoding=self._cw.encoding)
       
    44             if format:
       
    45                 self.cw_edited['data_format'] = text_type(format)
       
    46             if encoding:
       
    47                 self.cw_edited['data_encoding'] = text_type(encoding)
       
    48 
       
    49 
       
    50 class UnResizeable(Exception):
       
    51     pass