#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # @Version : Python 3.11.4 # @Software : Sublime Text 4 # @Author : StudentCWZ # @Email : StudentCWZ@outlook.com # @Date : 2023/10/29 00:36 # @File : dsn.py # @Description : """ class DatabaseURI: """ The DatabaseURI class is a utility for generating SQLAlchemy database connection strings for various types of databases. :param db_type: The type of the database. It could be "mysql", "postgresql", "oracle", "sqlite". :param username: The username of the database. Not required for "sqlite". :param password: The password of the database. Not required for "sqlite". :param host: The host of the database. Not required for "sqlite". :param port: The port of the database. Not required for "sqlite". :param db: The database name. For "sqlite", it is the path to the database file. :param driver: The python library to connect to the database. Not required but could be provided. """ def __init__(self, db_type: str, username: str = None, password: str = None, host: str = None, port: str = None, db: str = None, driver: str = None ) -> None: self.db_type = db_type self.username = username self.password = password self.host = host self.port = port self.db = db self.driver = driver def create(self) -> str: """ Creates a SQLAlchemy engine string for the specified database. :return: A SQLAlchemy engine string. """ # SQLite database only require a path to the database file if self.db_type == 'sqlite': return f'{self.db_type}:///{self.db}' else: # Other databases require a full connection string with optional driver if self.driver: return (f'{self.db_type}+{self.driver}://' f'{self.username}:{self.password}@{self.host}:{self.port}/{self.db}') else: return f'{self.db_type}://{self.username}:{self.password}@{self.host}:{self.port}/{self.db}' def __repr__(self): return f'' def __str__(self): return self.create()