I want to get this code reviewed for a function I wrote that pulls log messages from a MySQL table:
def get_logs_messages(request_id, destination=None):
"""
get logs from deployment table
:param int request_id: request id of selected deployment.
:param str destination: destination site
:return: list of messagesfor selected deployment based on request id.
:rtype: list
"""
conn = MySQLdb.connect(**dbconfig)
query = "SELECT deployment_id " \
"from deployment " \
"WHERE request_id={request_id} " \
" {dest}".format(
request_id=request_id,
dest="AND DESTINATION = '{loc}'".format(loc=destination) if destination else "")
cursor = conn.cursor()
cursor.execute(query)
data = cursor.fetchall()
cursor.close()
msgs = []
for item in data:
query = "SELECT modified_dt , message from scripts_deployment_logs WHERE deployment_id = {}".format(item[0])
cursor = conn.cursor()
cursor.execute(query)
result = cursor.fetchall()
for dt, msg in result:
msgs.append("{dt}: {msg}".format(dt=str(dt), msg=msg))
cursor.close()
conn.close()
return msgs
I get a request ID from a web interface which is using a REST API to call this function, and this function retrieves the deployment id based on which it displays the logs. I am not very fluent with the MySQL part so I have used mysql.connector
with simple SQL queries.