@@ -185,6 +185,29 @@ def from_bytes(
185185
186186 return deserializer .deserialize (data )
187187
188+ def to_bytes (
189+ self , serializer : Optional [MetadataSerializer ] = None
190+ ) -> bytes :
191+ """Return the serialized TUF file format as bytes.
192+
193+ Arguments:
194+ serializer: A MetadataSerializer instance that implements the
195+ desired serialization format. Default is JSONSerializer.
196+
197+ Raises:
198+ tuf.api.serialization.SerializationError:
199+ The metadata object cannot be serialized.
200+ """
201+
202+ if serializer is None :
203+ # Use local scope import to avoid circular import errors
204+ # pylint: disable=import-outside-toplevel
205+ from tuf .api .serialization .json import JSONSerializer
206+
207+ serializer = JSONSerializer (compact = True )
208+
209+ return serializer .serialize (self )
210+
188211 def to_dict (self ) -> Dict [str , Any ]:
189212 """Returns the dict representation of self."""
190213
@@ -214,15 +237,10 @@ def to_file(
214237 The file cannot be written.
215238 """
216239
217- if serializer is None :
218- # Use local scope import to avoid circular import errors
219- # pylint: disable=import-outside-toplevel
220- from tuf .api .serialization .json import JSONSerializer
221-
222- serializer = JSONSerializer (compact = True )
240+ bytes_data = self .to_bytes (serializer )
223241
224242 with tempfile .TemporaryFile () as temp_file :
225- temp_file .write (serializer . serialize ( self ) )
243+ temp_file .write (bytes_data )
226244 persist_temp_file (temp_file , filename , storage_backend )
227245
228246 # Signatures.
0 commit comments