问题描述
只有在必要时,Python才可能将某个条件作为参数传递给函数吗? 例如:完整的if条件:
# /!\ checking if customer_name is NULL (NOT NULL field in destination database)
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
我正在研究一个脚本,该脚本将自动将数据从mysql迁移到postgresql。 一些表在两个数据库(源数据库和目标数据库)中具有相同的结构,另一些表在结构上不同,而另一些表仅在数据类型上有所不同。
我试图了解是否有可能“将”条件“注入”函数中,以便对上段提到的所有3种情况使用相同的代码。条件每次都会不同。
以下是一个示例(我正在调查注入可能性的代码段为黄色->将其作为参数传递):
def migrate_table(select_query, insert_query, tmp_args):
# Cursors initialization
cur_psql = cnx_psql.cursor()
cur_msql.execute(select_query)
args = []
for row in cur_msql:
# /!\ checking if customer_name is NULL (NOT NULL field in destination database)
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
args.append(cur_psql.mogrify(tmp_args, row))
args_str = ','.join(args)
if len(args_str) > 0:
try:
cur_psql.execute(insert_query + args_str)
except psycopg2.Error as e:
print "Cannot execute that query", e.pgerror
sys.exit("Leaving early this lucky script")
## Closing cursors
cur_psql.close()
实际上,我以这种方式调用函数:
migrate_compatable(
"SELECT customer_id, customer_name, contact_name, address, city, postal_code, country FROM mysqlcustomers",
"INSERT INTO psqlcustomers (customer_id, customer_name, contact_name, address, city, postal_code, country"
"(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)"
)
我想知道是否有可能添加一个输入完整条件的参数
1楼
正如@jonrsharpe建议你可以修改你migrate_table
函数传递一个检查功能,您将与调用row
:
def check_customer_name(row):
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
return row
然后在migrate_table
:
def migrate_table(..., check_function = None):
...
if callable(check_function):
row = check_function(row)
...
您的电话将变成:
migrate_table("...long sql query...", "...", check_customer_name)
您可以根据需要创建任意数量的检查功能。