我有一个脚本,可以根据它通过命令行接收的输入运行许多不同的报告。所有报告从数据库中读取,并将结果作为 Pandas 数据帧对象返回。
下面是超类(省略了大量的属性getter和setter函数(:
import mysql.connector
import pandas as p
import config
class Report(object):
_connection = None
_cursor = None
def __init__(self):
self._user = config.user
self._password = config.password
self._host = config.host
self._database = config.database
self._port = config.port
self._body_text = "Hello,nnPlease find attached these reports:nn"
self._connection = mysql.connector.connect(user=self._user, password=self._password, db=self._database,
host=self._host, port=self._port)
self._cursor = self._connection.cursor()
@property
def user(self):
return self._user
@user.setter
def user(self, value):
self._user = value
. . .
@property
def body_text(self):
return self._body_text
@body_text.setter
def body_text(self, value):
self._body_text = value
def append_body_text(self, value):
self._body_text += value
def get_data(self, server_cursor, query, columns):
server_cursor.execute(self, query)
results = server_cursor.fetchall()
data = p.DataFrame(data=results, columns=[columns])
return data
def get_today(self):
return self.today
def close(self):
self._connection_web.close()
self._connection_raw.close()
@staticmethod
def insert_variables_into_sql_statement(query, external_data):
final_query = query % external_data
return final_query
@staticmethod
def create_string_from_column(serial):
created_list = serial.tolist()
string = ', '.join(map(str, created_list))
return string
@staticmethod
def write_to_csv(data_frame, file_name):
data_frame.to_csv(config.baseDirectory + file_name, sep=',', index=False)
def generate_report(self):
data = self.get_data(self._cursor_web, self._query, self._columns)
self.write_to_csv(data, self._filename)
self.close()
以下是我的子类的结构:
class ExampleReport(Report):
def __init__(self):
Report.__init__(self)
self._query = """
SELECT
u.first_name AS 'First Name',
u.last_name AS 'Last Name'
FROM users AS u
"""
self._columns = "'FirstName', 'LastName'"
self._filename = "example_report.csv"
self.append_body_text("* All users")
在我的主方法中,我像这样调用该方法:
report = Reports.ExampleReport()
report.generate_report()
当我这样做时,我收到以下错误:
AttributeError: 'ExampleReport' object has no attribute 'encode'
我的数据库连接在构造糟糕的过程代码(工作版本目前正在生产中(时没有问题。现在它已经坏了,我已经尝试让它面向对象。有人知道我做错了什么吗?
编辑:解决了我自己的问题!在超类的get_data
函数中,第二行包含一个错误的self
参数传递到server_cursor.execute(query)
行中。一旦它被取出,错误就会消失。
解决了我自己的问题!在超类的get_data函数中,第二行包含一个错误的 self 参数,该参数传递到 server_cursor.execute(query( 行中。一旦它被取出,错误就会消失。