如何在适当的位置键入转换函数的多个参数? [英] How can I type convert many arguments of a function in place?

查看:28
本文介绍了如何在适当的位置键入转换函数的多个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CherryPy 来提供一个简单的网页,该网页根据 URL 参数显示不同的内容.具体来说,它取参数的总和并基于此显示不同的消息.在 CherryPy 中,网页可以定义为函数,URL 参数作为参数传递给该函数.
正如在本教程中解释的那样 URL 参数作为字符串传递,因此为了计算总和,我想将每个参数转换为浮点数.我会有很多URL参数,所以一个一个的做起来似乎很麻烦.

I use CherryPy to serve a simple webpage that shows different content based on the URL parameters. Specifically it takes the sum of the parameters and shows a different message based on that. In CherryPy webpages can be defined as functions, and URL parameters are passed as an argument to that function.
As explained in this tutorial URL parameters are passed as strings, so to calculate the sum I want to convert each argument to a float. I will have many URL parameters, so doing this one by one seems cumbersome.

如何在适当位置输入转换(大量)参数?

哑巴"方法是简单地获取每个参数并将其重新分配为浮点数:

The "dumb" approach would be to simply take each argument and re-assign it as a float:

def dumb(a="0", b="0", c="0", d="0", e="0", f="0", g="0"):
    a = float(a)
    b = float(b)
    c = float(c)
    d = float(d)
    e = float(e)
    f = float(f)
    g = float(g)

    return print(sum([a, b, c, d, e, f, g]))

它具有可读性,但相当重复,而且不是很pythonic".

It's readable, but rather repetitive and not very "pythonic".

我发现的另一个选择是将本地人重新分配给字典,然后循环遍历它并从字典中调用值.

Another option I found is to re-assign the locals to a dictionary, then loop over it and call the values from the dict.

def looping_dict(a="0", b="0", c="0", d="0", e="0", f="0", g="0"):
    args = locals()
    for key in args:
        if key in ["a", "b", "c", "d", "e", "f", "g"]:
            args[key] = float(args[key])

    return print(sum([args["a"], args["b"], args["c"], args["d"], args["e"], args["f"], args["g"]] ) )

这有点烦人,因为我每次都必须参考字典.所以一个简单的引用 d 变成了 args[d"].也无助于代码可读性.

This is a bit annoying as I have to reference the dictionary every time. So a simple reference d becomes args["d"]. Doesn't help code readability neither.

推荐答案

这仅记录在变更日志中,但自 2016 年以来 使用 cherrypy >= 6.2.0 有一个 @cherrypy.tools.params 工具在做正是您想要的(前提是您使用支持类型注释的 Python 3 版本):

This is only documented in the changelog but since 2016 with cherrypy >= 6.2.0 there is a @cherrypy.tools.params tool doing exactly what you want (provided that you use a Python 3 version supporting type annotations):

import cherrypy


@cherrypy.tools.params()
def your_http_handler(
        a: float = 0, b: float = 0,
        c: float = 0, d: float = 0,
        e: float = 0, f: float = 0,
        g: float = 0,
):
    return str(a + b + c + d + e + f + g)

添加它的 PR 是 PR #1442 — 你可以探索它的用法通过查看那里的测试.

The PR that added it is PR #1442 — you can explore the usage by looking at the tests there.

如果您的 Python 由于某种原因过时,您可以这样做:

If your Python is old for some reason, you could do:

import cherrypy


def your_http_handler(**kwargs):
    # Validate that the right query args are present in the HTTP request:
    if kwargs.keys() ^ {'a', 'b', 'c', 'd', 'e', 'f', 'g'}:
        raise cherrypy.HTTPError(400, message='Got invalid args!')

    numbers = (float(num) for num in kwargs.values())  # generator expression won't raise conversion errors here
    try:
        return str(sum(numbers))  # this will actually call those `float()` conversions so we need to catch a `ValueError`
    except ValueError as val_err:
        raise cherrypy.HTTPError(
            400,
            message='All args should be valid numbers: {exc!s}'.format(exc=val_err),
        )

附言在您最初的帖子中,您使用了 return print(...) 这是错误的.print() 总是返回 None 所以你会发送 "None" 回 HTTP 客户端,而 print 的参数(arg) 只会在您运行服务器的终端中打印出来.

P.S. In your initial post you use return print(...) which is wrong. print() always returns None so you'd be sending "None" back to the HTTP client while the argument of print(arg) would be just printed out in your terminal where you run the server.

这篇关于如何在适当的位置键入转换函数的多个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆