DataOpsHub 6.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ """
2
+ **Note**
3
+
4
+ This program is an application of the main module 'database_handler'
5
+ in the sub-package 'databases', and it uses some of its attributes and/or functions.
6
+ YOU MAY REDISTRIBUTE this program along any other directory,
7
+ but keep in mind that the module is designed to work with absolute paths.
8
+
9
+ Purpose
10
+ -------
11
+ - This program loads data from various file types (CSV, Excel, ODS) into a MySQL database.
12
+ - The function 'upload_file_data' from 'database_handler' is utilised for this task.
13
+ - Parameters can be modified to suit different data files and database configurations.
14
+
15
+ For 'dtype_dict_obj' Usage, please refer the docs of parameter 'dtype_dict'
16
+ at 'upload_file_data' function
17
+
18
+ Data Type Options
19
+ -----------------
20
+ Refer to the following table for mapping Pandas data types to MySQL data types:
21
+
22
+ +--------------------------+---------------------+
23
+ | Pandas Data Type | MySQL Data Type |
24
+ +--------------------------+---------------------+
25
+ | `int64` | `BIGINT` |
26
+ | `int32` | `INTEGER` |
27
+ | `float64` | `DOUBLE` |
28
+ | `float32` | `FLOAT` |
29
+ | `bool` | `BOOLEAN` |
30
+ | `datetime64` | `DATETIME` |
31
+ | `timedelta[{time_unit}]` | `TIME` |
32
+ | `object` | `TEXT` or `VARCHAR` |
33
+ | `category` | `VARCHAR` |
34
+ +--------------------------+---------------------+
35
+
36
+ Data Files
37
+ ----------
38
+ - The 'input_file_obj' variable can be assigned a single file path or a list of paths.
39
+ - Alternatively, 'find_files' from the 'path_utils' module can be used to search for files,
40
+ either for glob strings or for extensions.
41
+ """
42
+
43
+ #------------------------#
44
+ # Import project modules #
45
+ #------------------------#
46
+
47
+ from DataOpsHub.databases.database_handler import upload_file_data
48
+ from filewise.file_operations.path_utils import find_files
49
+ from paramlib.config_params import DATABASE_CREDENTIALS
50
+
51
+ #-------------------#
52
+ # Define parameters #
53
+ #-------------------#
54
+
55
+ # Database type #
56
+ #---------------#
57
+
58
+ DATABASE_TYPE = "mysql"
59
+
60
+ # Table parameters #
61
+ #------------------#
62
+
63
+ TABLE_PARAM_DICT = dict(
64
+ if_exists="replace",
65
+ import_index=False,
66
+ separator="\t",
67
+ header=0,
68
+ parser_engine=None,
69
+ decimal=","
70
+ )
71
+
72
+ # Data type dictionary to apply for one or more sheets #
73
+ #------------------------------------------------------#
74
+
75
+ DTYPE_DICT_OBJ = {
76
+ 'column1': 'int64',
77
+ 'column2': 'float64',
78
+ 'column3': 'object'
79
+ }
80
+
81
+ # DTYPE_DICT_OBJ = [
82
+ # {
83
+ # 'file1_column1': 'int64',
84
+ # 'file1_column2': 'float64',
85
+ # 'file1_column3': 'object'
86
+ # },
87
+ # {
88
+ # 'file2_column1': 'int64',
89
+ # 'file2_column2': 'float64',
90
+ # 'file2_column3': 'object'
91
+ # },
92
+ # ]
93
+
94
+ # DTYPE_DICT_OBJ = None
95
+
96
+ # Data files #
97
+ #------------#
98
+
99
+ INPUT_FILE_OBJ = "/home/jonander/Documents/gordetegiak/pygenutils.databases/test.csv"
100
+
101
+ # INPUT_FILE_OBJ = [
102
+ # "/home/jonander/Documents/gordetegiak/pygenutils/databases/test1.csv",
103
+ # "/home/jonander/Documents/gordetegiak/pygenutils/databases/test2.csv",
104
+ # "/home/jonander/Documents/gordetegiak/pygenutils/databases/test3.csv"
105
+ # ]
106
+
107
+ # INPUT_FILE_OBJ = find_files("test*", search_path=".", match_type="glob", top_path_only=True)
108
+ # INPUT_FILE_OBJ = find_files(".csv", search_path=".", match_type="ext", top_path_only=True)
109
+
110
+ #-------------#
111
+ # Run program #
112
+ #-------------#
113
+
114
+ upload_file_data(INPUT_FILE_OBJ,
115
+ DATABASE_CREDENTIALS,
116
+ database_type=DATABASE_TYPE,
117
+ **TABLE_PARAM_DICT,
118
+ dtype_dict=DTYPE_DICT_OBJ)
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Models package for DataOpsHub.
6
+
7
+ This package contains all the data models used in the application.
8
+ """
9
+
10
+ # Define what should be available when using 'from DataOpsHub.models import *'
11
+ __all__ = [
12
+ 'BaseModel',
13
+ 'LabResults',
14
+ 'MedicationsHistory',
15
+ 'User',
16
+ 'VitalSigns'
17
+ ]
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Base Model Module
6
+
7
+ This module defines the BaseModel class for the DataOpsHub application.
8
+ """
9
+
10
+ # Import modules #
11
+ #----------------#
12
+
13
+ from sqlalchemy import Column, String
14
+ from sqlalchemy.orm import declarative_base
15
+
16
+ # Declare objects #
17
+ #-----------------#
18
+
19
+ Base = declarative_base()
20
+
21
+ # Define classes #
22
+ #----------------#
23
+
24
+ class BaseModel(Base):
25
+ """
26
+ Base model class with common fields and methods for all models.
27
+
28
+ This class serves as a base for all other model classes in the application.
29
+ It provides common fields and methods that are shared across all models.
30
+ """
31
+ __abstract__ = True
32
+
33
+ # Common fields that all models should have
34
+ hl7_v2 = Column(String, nullable=True)
35
+
36
+ @classmethod
37
+ def get_user_id_field(cls):
38
+ """
39
+ Get the user ID field for this model.
40
+
41
+ Returns
42
+ -------
43
+ sqlalchemy.Column
44
+ The user ID column for this model.
45
+ """
46
+ from ..constants.table_mappings import TABLE_FIELD_MAPPING
47
+ if cls.__tablename__ in TABLE_FIELD_MAPPING:
48
+ field_name = TABLE_FIELD_MAPPING[cls.__tablename__]['id_field']
49
+ if field_name:
50
+ return getattr(cls, field_name)
51
+ return None
52
+
53
+ @classmethod
54
+ def get_date_field(cls):
55
+ """
56
+ Get the date field for this model.
57
+
58
+ Returns
59
+ -------
60
+ sqlalchemy.Column
61
+ The date column for this model.
62
+ """
63
+ from ..constants.table_mappings import TABLE_FIELD_MAPPING
64
+ if cls.__tablename__ in TABLE_FIELD_MAPPING:
65
+ field_name = TABLE_FIELD_MAPPING[cls.__tablename__]['date_field']
66
+ if field_name:
67
+ return getattr(cls, field_name)
68
+ return None
69
+
70
+ @classmethod
71
+ def register_model(cls, table_name: str):
72
+ """
73
+ Register the model in the MODEL_REGISTRY.
74
+
75
+ Parameters
76
+ ----------
77
+ table_name : str
78
+ The name of the table this model represents.
79
+ """
80
+ from ..databases.database_handler import MODEL_REGISTRY
81
+ MODEL_REGISTRY[table_name] = cls
82
+ return cls # Return the class to allow for decorator-style usage if needed
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ User Model Module
6
+
7
+ This module defines the User model for the DataOpsHub application.
8
+ """
9
+
10
+ # Import modules #
11
+ #----------------#
12
+
13
+ from datetime import datetime
14
+
15
+ from sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String, Text
16
+ from sqlalchemy.orm import relationship
17
+
18
+ # Import project modules #
19
+ #------------------------#
20
+
21
+ from DataOpsHub.models.base import BaseModel
22
+
23
+ # Define classes #
24
+ #----------------#
25
+
26
+ class User(BaseModel):
27
+ """
28
+ User model class representing a user in the system.
29
+ """
30
+ __tablename__ = 'users'
31
+
32
+ user_id = Column(String(10), primary_key=True)
33
+ first_name = Column(String(50), nullable=False)
34
+ last_name = Column(String(50), nullable=False)
35
+ date_of_birth = Column(DateTime, nullable=False)
36
+ gender = Column(String(10), nullable=False)
37
+ email = Column(String(100), unique=True, nullable=False)
38
+ phone = Column(String(15))
39
+ address = Column(Text)
40
+ created_at = Column(DateTime, default=datetime.utcnow)
41
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
42
+
43
+ # Relationships
44
+ vital_signs = relationship("VitalSigns", back_populates="user")
45
+ lab_results = relationship("LabResults", back_populates="user")
46
+ medications_history = relationship("MedicationsHistory", back_populates="user")
47
+
48
+ def __repr__(self):
49
+ return f"<User(user_id='{self.user_id}', name='{self.first_name} {self.last_name}')>"
50
+
51
+ # Register the model
52
+ User.register_model('users')
53
+
54
+ class VitalSigns(BaseModel):
55
+ """
56
+ Model for storing user vital signs measurements.
57
+ """
58
+ __tablename__ = 'vital_signs'
59
+
60
+ id = Column(Integer, primary_key=True)
61
+ user_id = Column(String(10), ForeignKey('users.user_id'))
62
+ timestamp = Column(DateTime, default=datetime.utcnow)
63
+ heart_rate = Column(Integer)
64
+ blood_pressure = Column(String(20))
65
+ temperature = Column(Float)
66
+ oxygen_saturation = Column(Integer)
67
+
68
+ user = relationship("User", back_populates="vital_signs")
69
+
70
+ # Register the model
71
+ VitalSigns.register_model('vital_signs')
72
+
73
+ class LabResults(BaseModel):
74
+ """
75
+ Model for storing user laboratory test results.
76
+ """
77
+ __tablename__ = 'lab_results'
78
+
79
+ id = Column(Integer, primary_key=True)
80
+ user_id = Column(String(10), ForeignKey('users.user_id'))
81
+ timestamp = Column(DateTime, default=datetime.utcnow)
82
+ test_name = Column(String(100))
83
+ result = Column(String(100))
84
+ unit = Column(String(20))
85
+ reference_range = Column(String(50))
86
+
87
+ user = relationship("User", back_populates="lab_results")
88
+
89
+ # Register the model
90
+ LabResults.register_model('lab_results')
91
+
92
+ class MedicationsHistory(BaseModel):
93
+ """
94
+ Model for tracking user medication history.
95
+ """
96
+ __tablename__ = 'medications_history'
97
+
98
+ id = Column(Integer, primary_key=True)
99
+ user_id = Column(String(10), ForeignKey('users.user_id'))
100
+ timestamp = Column(DateTime, default=datetime.utcnow)
101
+ medication_name = Column(String(100))
102
+ dosage = Column(String(50))
103
+ frequency = Column(String(50))
104
+ start_date = Column(DateTime)
105
+ end_date = Column(DateTime)
106
+
107
+ user = relationship("User", back_populates="medications_history")
108
+
109
+ # Register the model
110
+ MedicationsHistory.register_model('medications_history')
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Security package for DataOpsHub.
6
+
7
+ This package contains security-related functionality.
8
+ """
9
+
10
+ # Define what should be available when using 'from DataOpsHub.security import *'
11
+ __all__ = [
12
+ 'SecurityConfig',
13
+ 'SecurityError',
14
+ 'generate_password'
15
+ ]
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #----------------#
5
+ # Import modules #
6
+ #----------------#
7
+
8
+ import numpy as np
9
+
10
+ #------------------#
11
+ # Define functions #
12
+ #------------------#
13
+
14
+ def generate_automated_password(lower_char_idx,
15
+ upper_char_idx,
16
+ password_length):
17
+
18
+ # Parameters #
19
+ #------------#
20
+
21
+ # Output info elements #
22
+ key_expl = "Automatically generated password"
23
+ lke = len(key_expl)
24
+ hashtag_underliner = '#' * lke
25
+
26
+ # List delimiter #
27
+ delim = ""
28
+
29
+ # Construct the password #
30
+ #------------------------#
31
+
32
+ # Get the corresponding unicode string list #
33
+ chars_glob = [chr(i) for i in range(lower_char_idx, upper_char_idx)]
34
+ lcg = len(chars_glob)
35
+
36
+ # Define random numbers ranging from 0 to the length of the list #
37
+ random_idx = np.random.randint(lcg, size=password_length)
38
+
39
+ # Select unicode strings according to these random numbers #
40
+ char_randomsel_list = [chars_glob[j] for j in random_idx]
41
+
42
+ # Convert the list to string #
43
+ passwd = delim.join(char_randomsel_list)
44
+
45
+ # Output the password with formatted printing #
46
+ passwd_str = f"{key_expl}\n{hashtag_underliner}\n{passwd}"
47
+ return passwd_str
48
+
49
+ #--------------------#
50
+ # Call the functions #
51
+ #--------------------#
52
+
53
+ automated_passwd = generate_automated_password(31, 127, 16)
54
+ print(automated_passwd)
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Configuration Module
6
+
7
+ This module provides configuration settings for the DataOpsHub application.
8
+ """
9
+
10
+ import os
11
+ from datetime import timedelta
12
+
13
+ # Database configuration
14
+ DATABASE_TYPE = os.getenv('DATABASE_TYPE', 'mysql')
15
+ DATABASE_HOST = os.getenv('DATABASE_HOST', 'localhost')
16
+ DATABASE_PORT = os.getenv('DATABASE_PORT', '3306')
17
+ DATABASE_NAME = os.getenv('DATABASE_NAME', 'dataopshub')
18
+ DATABASE_USER = os.getenv('DATABASE_USER', 'root')
19
+ DATABASE_PASSWORD = os.getenv('DATABASE_PASSWORD', '')
20
+
21
+ # Security configuration
22
+ SECRET_KEY = os.getenv('SECRET_KEY', 'your-secret-key-here')
23
+ JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'your-jwt-secret-key-here')
24
+ JWT_ACCESS_TOKEN_EXPIRES = timedelta(hours=1)
25
+ JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=30)
26
+ PASSWORD_RESET_TOKEN_EXPIRES = timedelta(hours=1)
27
+
28
+ # Application configuration
29
+ DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'
30
+ TESTING = os.getenv('TESTING', 'False').lower() == 'true'
31
+ ENVIRONMENT = os.getenv('ENVIRONMENT', 'development')
32
+
33
+ # API configuration
34
+ API_PREFIX = '/api/v1'
35
+ API_TITLE = 'DataOpsHub API'
36
+ API_VERSION = '1.0.0'
37
+ API_DESCRIPTION = 'API for the DataOpsHub application'
38
+
39
+ # CORS configuration
40
+ CORS_ORIGINS = os.getenv('CORS_ORIGINS', '*').split(',')
41
+
42
+ # Logging configuration
43
+ LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
44
+ LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
45
+ LOG_FILE = os.getenv('LOG_FILE', 'dataopshub.log')
46
+
47
+ # Email configuration
48
+ SMTP_HOST = os.getenv('SMTP_HOST', 'smtp.gmail.com')
49
+ SMTP_PORT = int(os.getenv('SMTP_PORT', '587'))
50
+ SMTP_USER = os.getenv('SMTP_USER', '')
51
+ SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
52
+ SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'True').lower() == 'true'
53
+ EMAIL_FROM = os.getenv('EMAIL_FROM', 'noreply@dataopshub.com')
54
+
55
+ # File upload configuration
56
+ UPLOAD_FOLDER = os.getenv('UPLOAD_FOLDER', 'uploads')
57
+ MAX_CONTENT_LENGTH = int(os.getenv('MAX_CONTENT_LENGTH', '16777216')) # 16MB
58
+ ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
59
+
60
+ # Cache configuration
61
+ CACHE_TYPE = os.getenv('CACHE_TYPE', 'simple')
62
+ CACHE_DEFAULT_TIMEOUT = int(os.getenv('CACHE_DEFAULT_TIMEOUT', '300')) # 5 minutes
63
+ CACHE_REDIS_HOST = os.getenv('CACHE_REDIS_HOST', 'localhost')
64
+ CACHE_REDIS_PORT = int(os.getenv('CACHE_REDIS_PORT', '6379'))
65
+ CACHE_REDIS_PASSWORD = os.getenv('CACHE_REDIS_PASSWORD', '')
66
+ CACHE_REDIS_DB = int(os.getenv('CACHE_REDIS_DB', '0'))
67
+
68
+ # Rate limiting configuration
69
+ RATELIMIT_DEFAULT = os.getenv('RATELIMIT_DEFAULT', '200 per day')
70
+ RATELIMIT_STORAGE_URL = os.getenv('RATELIMIT_STORAGE_URL', 'memory://')
71
+
72
+ # Session configuration
73
+ SESSION_TYPE = os.getenv('SESSION_TYPE', 'filesystem')
74
+ SESSION_FILE_DIR = os.getenv('SESSION_FILE_DIR', 'flask_session')
75
+ SESSION_PERMANENT = os.getenv('SESSION_PERMANENT', 'False').lower() == 'true'
76
+ PERMANENT_SESSION_LIFETIME = timedelta(days=1)
77
+
78
+ # Security headers configuration
79
+ SECURITY_HEADERS = {
80
+ 'X-Content-Type-Options': 'nosniff',
81
+ 'X-Frame-Options': 'SAMEORIGIN',
82
+ 'X-XSS-Protection': '1; mode=block',
83
+ 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
84
+ 'Content-Security-Policy': "default-src 'self'",
85
+ 'Referrer-Policy': 'strict-origin-when-cross-origin'
86
+ }
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Exceptions Module
6
+
7
+ This module defines custom exceptions for the DataOpsHub application.
8
+ """
9
+
10
+ class DataOpsHubError(Exception):
11
+ """
12
+ Base exception class for DataOpsHub.
13
+ """
14
+ pass
15
+
16
+ class DatabaseError(DataOpsHubError):
17
+ """
18
+ Exception raised for database-related errors.
19
+ """
20
+ pass
21
+
22
+ class ValidationError(DataOpsHubError):
23
+ """
24
+ Exception raised for validation errors.
25
+ """
26
+ pass
27
+
28
+ class AuthenticationError(DataOpsHubError):
29
+ """
30
+ Exception raised for authentication errors.
31
+ """
32
+ pass
33
+
34
+ class AuthorisationError(DataOpsHubError):
35
+ """
36
+ Exception raised for authorisation errors.
37
+ """
38
+ pass
39
+
40
+ class NotFoundError(DataOpsHubError):
41
+ """
42
+ Exception raised when a requested resource is not found.
43
+ """
44
+ pass
45
+
46
+ class ConflictError(DataOpsHubError):
47
+ """
48
+ Exception raised when there is a conflict with an existing resource.
49
+ """
50
+ pass
51
+
52
+ class ServiceError(DataOpsHubError):
53
+ """
54
+ Exception raised for service-related errors.
55
+ """
56
+ pass
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Services package for DataOpsHub.
6
+
7
+ This package contains all the service classes used in the application.
8
+ """
9
+
10
+ # Define what should be available when using 'from DataOpsHub.services import *'
11
+ __all__ = [
12
+ 'DataRetrievalService',
13
+ 'UserService'
14
+ ]