gpt4 book ai didi

python - 将数据库连接传递给另一个类

转载 作者:行者123 更新时间:2023-12-01 06:01:04 26 4
gpt4 key购买 nike

我有两个类,一个使用selenium浏览互联网,另一个将数据插入mysql数据库。

class DBConnection:
def __init__(self, db_host=DB_HOST, db_port=DB_PORT, db_user=DB_USER, db_password=DB_PASSWORD, db_name=DB_NAME):
self.host = DB_HOST
self.port = DB_PORT
self.name = DB_NAME
self.user = DB_USER
self.password = DB_PASSWORD
self.conn = None
self.cursor = None

class WebDriver:
def __init__(self, download_folder=DOWNLOAD_FOLDER):
self.driver = False

def start_webdriver(self):
"""
Initiate a Firefox profile for Selenium WebDriver.
"""
fp = webdriver.FirefoxProfile()
self.driver = webdriver.Firefox(firefox_profile=fp)

从 WebDriver 类获取数据库连接的最佳方法是什么?像这样的东西会起作用吗?

class WebDriver:
def __init__(self, download_folder=DOWNLOAD_FOLDER):
self.driver = False
self.download_folder = download_folder
self.last_payment = None
self.DBConnection = DBConnection()
self.DBConnection.get_conn()
self.DBConnection.get_cursor()

最佳答案

首先,您初始化 DBConnection 是错误的!应该是

class DBConnection(object):
def __init__(self, db_host=DB_HOST, db_port=DB_PORT, db_user=DB_USER, db_password=DB_PASSWORD, db_name=DB_NAME):
self.host = db_host # lower case!
self.port = db_port
self.name = db_name
self.user = db_user
self.password = db_password

然后您可以允许用户指定设置,如下所示:

class WebDriver(object):
def __init__(self, download_folder=DOWNLOAD_FOLDER, **kwargs):
self.driver = False
self.download_folder = download_folder
self.last_payment = None
self.DBConnection = DBConnection(**kwargs)
self.DBConnection.get_conn()
self.DBConnection.get_cursor()

关于python - 将数据库连接传递给另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10456535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com