s3Service.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import boto3
  2. import json
  3. import config as cf
  4. class S3Service:
  5. """
  6. This class is intended to have helper methods for operations in s3.
  7. ...
  8. Methods
  9. --------
  10. validFileChecker(file_name)
  11. Checks the extension of the file and returns if the file is valid or not.
  12. """
  13. def vald_file_checker(self, file_name):
  14. """Returns "valid" if the file extension is of csv, hl7, json else returns invalid.
  15. Parameters
  16. ----------
  17. file_name : str
  18. File_name in string format
  19. Returns
  20. --------
  21. string
  22. Returns "valid" or "invalid" based on the extensionw
  23. """
  24. if("." in file_name):
  25. file_name_split = file_name.split(".")
  26. extension = file_name_split[1]
  27. check = ["csv","hl7","json"]
  28. if(extension not in check):
  29. print(cf.respomseMessage['fileFormat'])
  30. return "invalid"
  31. else:
  32. #if the file-name doesn't have any extension return invalid
  33. return "invalid"
  34. return extension
  35. def upload_file_tos3(self,bucket_name,file_name,file_content):
  36. """Methof to upload file to s3.
  37. Parameters
  38. ----------
  39. bucket_name : string
  40. Name of the bucket, where the file need to be uploaded.
  41. file_name : string
  42. file which need to be uploaded to bucket
  43. file_content: json
  44. The content which is being uploaded to s3 with it's name as file_name
  45. """
  46. s3 = boto3.client("s3")
  47. s3_file_path = cf.constants['s3_folder_path']
  48. #s3.put_object is the method provided by boto3 to upload file.
  49. response_upload_object = s3.put_object(Bucket=bucket_name, Key=s3_file_path+file_name,Body=file_content)
  50. print("The response upload object is",response_upload_object)
  51. # #print("The extension of the file is ",magic.from_file(fileContent, mime = True))
  52. return response_upload_object