_datastream.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import io
  17. import sys
  18. import json
  19. # Datastream is a wraper of StringIO, it receives kv pairs and dump it to json string
  20. class Datastream(object):
  21. def __init__(self):
  22. self._string = io.StringIO()
  23. self._string.write("[")
  24. def get_size(self):
  25. return sys.getsizeof(self._string.getvalue())
  26. def get_data(self):
  27. self._string.write("]")
  28. return self._string.getvalue()
  29. def append(self, kv: dict):
  30. # add ',' if not the first element
  31. if self._string.getvalue() != "[":
  32. self._string.write(",")
  33. json.dump(kv, self._string)
  34. def clear(self):
  35. self._string.close()
  36. self.__init__()