nextcloud.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """
  2. We are implementing transport to and from nextcloud (just like s3)
  3. """
  4. import os
  5. import sys
  6. from transport.common import Reader,Writer, IEncoder
  7. import pandas as pd
  8. from io import StringIO
  9. import json
  10. import nextcloud_client as nextcloud
  11. class Nextcloud :
  12. def __init__(self,**_args):
  13. pass
  14. self._delimiter = None
  15. self._handler = nextcloud.Client(_args['url'])
  16. _uid = _args['uid']
  17. _token = _args['token']
  18. self._uri = _args['folder'] if 'folder' in _args else './'
  19. if self._uri.endswith('/') :
  20. self._uri = self._uri[:-1]
  21. self._file = None if 'file' not in _args else _args['file']
  22. self._handler.login(_uid,_token)
  23. def close(self):
  24. try:
  25. self._handler.logout()
  26. except Exception as e:
  27. pass
  28. class NextcloudReader(Nextcloud,Reader):
  29. def __init__(self,**_args):
  30. # self._file = [] if 'file' not in _args else _args['file']
  31. super().__init__(**_args)
  32. pass
  33. def read(self,**_args):
  34. _filename = self._file if 'file' not in _args else _args['file']
  35. #
  36. # @TODO: if _filename is none, an exception should be raised
  37. #
  38. _uri = '/'.join([self._uri,_filename])
  39. if self._handler.get_file(_uri) :
  40. #
  41. #
  42. _info = self._handler.file_info(_uri)
  43. _content = self._handler.get_file_contents(_uri).decode('utf8')
  44. if _info.get_content_type() == 'text/csv' :
  45. #
  46. # @TODO: enable handling of csv, xls, parquet, pickles
  47. _file = StringIO(_content)
  48. return pd.read_csv(_file)
  49. else:
  50. #
  51. # if it is neither a structured document like csv, we will return the content as is
  52. return _content
  53. return None
  54. class NextcloudWriter (Nextcloud,Writer):
  55. """
  56. This class will write data to an instance of nextcloud
  57. """
  58. def __init__(self,**_args) :
  59. super().__init__(**_args)
  60. self
  61. def write(self,_data,**_args):
  62. """
  63. This function will upload a file to a given destination
  64. :file has the uri of the location of the file
  65. """
  66. _filename = self._file if 'file' not in _args else _args['file']
  67. _uri = '/'.join([self._uri,_filename])
  68. if type(_data) == pd.DataFrame :
  69. f = StringIO()
  70. _data.to_csv(f,index=False)
  71. _content = f.getvalue()
  72. elif type(_data) == dict :
  73. _content = json.dumps(_data,cls=IEncoder)
  74. else:
  75. _content = str(_data)
  76. self._handler.put_file_contents(_uri,_content)