Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

push_data.py 2.3 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  1. import os
  2. import sys
  3. import json
  4. from dotenv import load_dotenv
  5. # Load environment variables
  6. load_dotenv()
  7. # Get MongoDB URI from environment variable
  8. uri = os.getenv('MONGODB_URI')
  9. print("MongoDB URI:", uri)
  10. import certifi #root certificate for http connection and store in ca(certificate authority)
  11. ca=certifi.where()
  12. import pandas as pd
  13. import numpy as np
  14. import pymongo
  15. from networksecurity.exception.exception import NetworkSecurityException
  16. from networksecurity.logging.logger import logging
  17. class NetworkDataExtract():
  18. def __init__(self):
  19. try:
  20. self.client = pymongo.MongoClient(uri, tlsCAFile=ca)
  21. self.db = self.client['network_security']
  22. self.collection = self.db['network_data']
  23. logging.info("MongoDB connection established successfully")
  24. except Exception as e:
  25. logging.error("Error while connecting to MongoDB")
  26. raise NetworkSecurityException(e, sys) from e
  27. def csv_to_json_converter(self, file_path):
  28. try:
  29. df = pd.read_csv(file_path)
  30. if df.empty:
  31. raise ValueError("CSV file is empty.")
  32. df.reset_index(drop=True, inplace=True)
  33. records = list(json.loads(df.T.to_json()).values())
  34. return records
  35. except Exception as e:
  36. raise NetworkSecurityException(e, sys)
  37. def insert_data_mongodb(self, records, database, collection):
  38. try:
  39. # Initialize MongoDB client and access specified database and collection
  40. mongo_client = pymongo.MongoClient(uri, tlsCAFile=ca)
  41. db = mongo_client[database]
  42. collection = db[collection]
  43. # Insert records into the collection
  44. collection.insert_many(records)
  45. return len(records)
  46. except Exception as e:
  47. raise NetworkSecurityException(e, sys)
  48. if __name__ == "__main__":
  49. file_path = "Network_Data/cyber_threat_intelligence_train.csv"
  50. database = "AUSTINAI"
  51. collection = "network_data"
  52. network_data_extract = NetworkDataExtract()
  53. records = network_data_extract.csv_to_json_converter(file_path)
  54. num_records = network_data_extract.insert_data_mongodb(records, database, collection)
  55. print(f"Inserted {num_records} records into MongoDB")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...