【问题标题】:How to dynamically change the output from a function based on the arguments passed?如何根据传递的参数动态更改函数的输出?
【发布时间】:2019-04-18 21:10:36
【问题描述】:

我正在尝试在 python 中构建一个函数,该函数根据用户传递的参数返回输出。

以下是基本功能:

def report():
    db_conn
    dwh_cursor = conn.cursor()  # set DB Cursor

    ## Query
    dwh_cursor.execute(sql.SQL("""select name,class,team,position from students"""))

上述函数在执行时工作正常。我在这里要修改的是当我传递一个带有值的参数时,只有该列应该在函数的输出中返回。例如,在下面的函数中,我只传递了两个参数,即名称和类,我希望输出中只有这两个值,如下所示:

def report(name,class,team,position):
    db_conn
    dwh_cursor = conn.cursor()  # set DB Cursor

    ## Query
    dwh_cursor.execute(sql.SQL("""select name,class,team,position from students"""))

report("Scott","High_School","","")

Expected query to be executed:

    ## Query
    dwh_cursor.execute(sql.SQL("""select (%s),(%s) from students"""), (name,class))

谁能指导我如何获得这个指定的输出?

【问题讨论】:

    标签: python python-3.x function arguments


    【解决方案1】:

    您可能会发现传递要检索的列名列表更容易。

    def report(*field_names):
        db_conn
        dwh_cursor = conn.cursor()  # set DB Cursor
    
        if not field_names:
            field_names = ('name', 'class', 'team', 'position')
    
        ## Query
        dwh_cursor.execute('select {} from students'.format(', '.join(field_names)))
        ...
    
    report('name', 'class')
    

    健康警告

    1. 根据用户输入动态生成 sql 是有风险的(即,如果未知/不受信任的用户可以设置放入查询的文本,那么他们可能会大大改变您正在运行的查询)

    2. 如果这是要支持的大型应用程序的一部分,您可能会受益于 ORM 工具(例如 sqlalchemy)来为您处理与数据库的接口

    【讨论】:

    • 感谢您的回复。我看到当我尝试执行上述查询时,它只是继续处理而没有任何消息..使用与您建议的完全相同的输入..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2014-10-28
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多