예제 #1
0
    def to_xml(self, s: BuilderState) -> BuilderState:
        _E = getattr(E, self.tag)

        content_type = guess_type(self.file)
        file_size = str(self.file.stat().st_size)

        if s.embedded:
            # load the file and embed into a data-uri
            # NOTE - currently we read entire file into memory first prior to b64 encoding,
            #  to consider using base64io-python to stream and encode in 1-pass
            content = b64encode(self.file.read_bytes()).decode()
            e = _E(
                type=content_type,
                size=file_size,
                **self.attributes,
                src=f"data:{content_type};base64,{content}",
            )
        else:
            e = _E(
                type=guess_type(self.file),
                size=file_size,
                **self.attributes,
                src=f"attachment://{s.attachment_count}",
            )

        if self.caption:
            e.append(E.Caption(self.caption))
        return s.add_element(self, e, self.file)
예제 #2
0
 def mk_file_fields(field_name: str, f: Path):
     # compress the file, in-place
     # TODO - disable compression where unneeded, e.g. .gz, .zip, .png, etc
     with compress_file(f) as f_gz:
         return (
             field_name,
             (f.name, open(f_gz, "rb"), guess_type(f), file_header),
         )
예제 #3
0
 def mime(self) -> MIME:
     return guess_type(self.file)