Skip to content

Commit

Permalink
Basic export as csv.
Browse files Browse the repository at this point in the history
  • Loading branch information
kiarn committed Oct 7, 2024
1 parent b957ba7 commit dfd1403
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import csv
from dataclasses import dataclass, asdict


Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import re
import ldap
import csv
import logging
from datetime import datetime

from linuxmusterTools.ldapconnector.ldap_reader import LdapReader

Expand Down Expand Up @@ -91,6 +93,31 @@ def getvalues(self, url, attributes, dict=True, **kwargs):
else:
return {attr: getattr(results, attr, None) for attr in attrs}

def ascsv(self, url, delimiter=";", csvfile=None, attributes=[], header=True, **kwargs):
if not csvfile:
# TODO: find a better path
obj_type = url.split('/')[1]
now = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
csvfile = f'/tmp/export_csv_{obj_type}_{now}.csv'

data = self.get(url, attributes=attributes, dict=True, **kwargs)
if not isinstance(data, list):
data = [data]

headers = list(data[0].keys())

with open(csvfile, 'w') as csv_io:
csv_writer = csv.writer(csv_io, delimiter=delimiter)

if header:
csv_writer.writerow(headers)

for entry in data:
csv_writer.writerow([entry[field] for field in headers])

logging.info(f"CSV file successfully exported to {csvfile}")
print(f"CSV file successfully exported to {csvfile}")

def add_url(self, url, method):
"""
Check collisions between URLs before adding to self.urls.
Expand Down

0 comments on commit dfd1403

Please sign in to comment.