任何人都可以帮我简化我的代码..我使用相同的功能制作了5个不同的功能,唯一的区别是列表中的名称将显示信息。
请告诉我如何缩短它。
我的代码:
def country():
cur = mysql.connection.cursor()
cur.callproc('spGetAllCountry')
data = cur.fetchall()
country_list=[];
for country in data:
i = {
'Name' : country[2],
'Code' : country[0],
'Description' : country[1]
}
country_list.append(i)
return jsonify(country_list)
def currency():
cur = mysql.connection.cursor()
cur.callproc('spGetAllCurrency')
data = cur.fetchall()
currency_list=[];
for currency in data:
i = {
'Name' : currency[2],
'Code' : currency[0],
'Description' : currency[1]
}
currency_list.append(i)
return jsonify(currency_list)
def paymentbrand():
cur = mysql.connection.cursor()
cur.callproc('spGetPaymentbrand')
data = cur.fetchall()
paymentbrand_list=[];
for paymentbrand in data:
i = {
'Name' : paymentbrand[2],
'Code' : paymentbrand[0],
'Description' : paymentbrand[1],
'Payment Code' : paymentbrand[3]
}
paymentbrand_list.append(i)
return jsonify(paymentbrand_list)
def paymentmode():
cur = mysql.connection.cursor()
cur.callproc('spGetPaymentmode')
data = cur.fetchall()
paymentmode_list=[];
for paymentmode in data:
i = {
'Name' : paymentmode[2],
'Code' : paymentmode[0],
'Description' : paymentmode[1]
}
paymentmode_list.append(i)
return jsonify(paymentmode_list)
答案 0 :(得分:0)
试试这个:
def get_data(func_name, value_idx_map):
cur = mysql.connection.cursor()
cur.callproc(func_name)
dataArr = cur.fetchall()
res=[]
for item in dataArr:
v = { key: item[idx] for key, idx in value_idx_map.items()}
res.append(v)
return pprint.pprint(res)
common_idx = {'Name': 2, 'Code': 0, 'Description': 1}
get_data('spGetAllCountry', common_idx)
get_data('spGetAllCurrency', common_idx)
get_data('spGetPaymentmode', common_idx)
common_idx['Payment Code'] = 3
get_data('spGetPaymentbrand', common_idx)