csv.py 977 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. __package__ = 'archivebox.index'
  2. from typing import List, Optional, Any
  3. from django.db.models import Model
  4. from ..util import enforce_types
  5. from .schema import Link
  6. @enforce_types
  7. def snapshots_to_csv(snapshots: List[Model],
  8. cols: Optional[List[str]]=None,
  9. header: bool=True,
  10. separator: str=',',
  11. ljust: int=0) -> str:
  12. cols = cols or ['timestamp', 'is_archived', 'url']
  13. header_str = ''
  14. if header:
  15. header_str = separator.join(col.ljust(ljust) for col in cols)
  16. row_strs = (
  17. snapshot.as_csv(cols=cols, ljust=ljust, separator=separator)
  18. for snapshot in snapshots
  19. )
  20. return '\n'.join((header_str, *row_strs))
  21. @enforce_types
  22. def to_csv(obj: Any, cols: List[str], separator: str=',', ljust: int=0) -> str:
  23. from .json import to_json
  24. return separator.join(
  25. to_json(getattr(obj, col), indent=None).ljust(ljust)
  26. for col in cols
  27. )