格式化字符串中的自定义参数

时间:2020-07-17 11:05:14

标签: python

我正在制作一个查询生成器,它接受一个可选的 where 条件。这些字段是通过Jupyter小部件界面插入的,只有填充的字段才进入最终查询。 查询是具有这种语法的字典(第一个版本):

query_1 : {
 q = ''' SELECT --stuff
FROM --db, joins
{where} ''',
 conditions : ['cond1','cond2',...]
}

查询引擎会检查小部件,如果有非空白字段,则会替换查询

if '{where}' in q:
    qw = ''
    conditions = 0
    evaluated_conditions = []
    ## add to a list every condition that needs be evaluated
    ## list is a 3-tuple: column name, comparison operator, filter value
    for cond_name, cval in zip(selected_query['conditions'], fields_text):
        if cval.value != '' and cval.value is not None:
            evaluated_conditions.append( ( cname,  '=', cval.value, ) )
            conditions += 1
    if conditions > 0:
        qw += 'WHERE\t'
        qw += "\nAND\t".join( [ f"{x} {y} '{z}'" for x, y, z in evaluated_conditions ] )
    q = q.format(where=qw)

现在出现了问题,我需要解析一个更长的查询,该查询已经包含一个where语句(骨架如下所示)。我需要通过在AND()语句中添加自定义值来对其进行格式化。

SELECT --stuff
FROM   --db, joins
WHERE  --static conditions
{and_} --AND condition

我唯一能想到的解决方案是复制代码。我觉得它很难看tbh:

if '{where}' in q:
    ## same as before
elif '{and_}' in q:
    qw = ''
    conditions = 0
    evaluated_conditions = []
    ## add to a list every condition that needs be evaluated
    ## list is a 3-tuple: column name, comparison operator, filter value
    for cond_name, cval in zip(selected_query['conditions'], fields_text):
        if cval.value != '' and cval.value is not None:
            evaluated_conditions.append( ( cname,  '=', cval.value, ) )
            conditions += 1
    if conditions > 0:
        qw += 'AND (\t'
        qw += "\nAND\t".join( [ f"{x} {y} '{z}'" for x, y, z in evaluated_conditions ] ) + ')'
    q = q.format(and_=qw)

由于两个代码段几乎完全相同(并且我可以更正不同的部分以使其完全相同,除了AND / WHERE条件除外),所以我想知道是否以及如何避免代码重复。否则,如果我需要重写代码流。

0 个答案:

没有答案