自动将参数格式化为字符串

2024-04-28 17:33:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个函数,它接受一些参数并构建一个SQL查询字符串。目前,我已经将每个关键字参数按名称分配给了字符串,我认为应该有一种更简单的方法来自动格式化字符串中预期的关键字参数。我想知道如果参数名称匹配,是否可以自动格式化(或分配)关键字参数到查询字符串。你知道吗

以下是我当前的功能:

def create_query(
    who_id,
    what_id=None,
    owner_id=None,
    subject,
    description,
    due_date,
    is_closed=False,
    is_priority=False,
    is_reminder=True,
    ):

    query_str = """
        'WhoId':'{who_id}',
        'Subject':'{subject}',
        'Description':'{description}',
        'ActivityDate':'{due_date}',
        'IsClosed':'{is_closed}',
        'IsPriority':'{is_priority}',
        'IsReminderSet':'{is_reminder}',
        """.format(
            who_id=who_id,
            subject=subject,               # Mapping each of these to the
            description=description,       # identically named variable
            due_date=due_date,             # seems dumb
            is_closed=is_closed,
            is_priority=is_priority,
            is_reminder=is_reminder,
            )

我想要更像这样的东西:

def create_query(**kwargs):
    query_string = """
         'WhoId':'{who_id}',
         'Subject':'{subject}',
         'Description':'{description}',
         ...
         """.format(
             for key in **kwargs:
                 if key == << one of the {keyword} variables in query_string >>:
                     key = << the matching variable in query_string >>

Tags: the字符串id参数dateis关键字description
1条回答
网友
1楼 · 发布于 2024-04-28 17:33:55
def create_query(**kwargs):
    query_string = """
         'WhoId':'{who_id}',
         'Subject':'{subject}',
         'Description':'{description}',
         ...
         """.format(**kwargs)
    print(query_string)

可以这样使用:

create_query(who_id=123, subject="Boss", description="he's bossy",
             will_be_ignored="really?")

印刷品:

         'WhoId':'123',
         'Subject':'Boss',
         'Description':'he is bossy',
         ...

注意我输入的附加参数will_be_ignored。它将被忽略。你不必自己过滤。你知道吗

但最好不要自己构建查询字符串。让数据库连接器来处理。例如,如果我的示例说“他很专横”,那么这将破坏查询,因为它使用'作为分隔符。数据库连接器应允许您使用占位符和值为其提供查询,然后使用值正确替换占位符。你知道吗

备选方案:

def create_query(**kwargs):
    parameters = (('WhoId', 'who_id'),
                  ('Subject','subject'),
                  ('Description', 'description'))
    query_string = ','.join(r"'{}':'{{{}}}'".format(name, kwargs[id])
                            for name, id in parameters
                            if id in kwargs)
    print(query_string)

create_query(who_id=123, description="he's bossy",
             will_be_ignored="really?")

印刷品:

'WhoId':'{123}','Description':'{he's bossy}'

相关问题 更多 >