2

我不是一个经验丰富的 Python 程序员,但我觉得我对这个问题的解决方案是不正确的,我认为在 Python 中有更好的方法来处理这个问题。

在这种情况下,这是使用Hug API,但这可能几乎无关紧要。

假设代码是这样的:

@hug.get_post('/hello')
def hello (name)
   print(type(name))
   return name

name当使用参数的一个实例发送请求时,该hello函数会获得str- 如下所示:

POST /hello?name=Bob

但是如果请求发送多个name参数,该方法接收一个list字符串,如

POST /hello?name=Bob&name=Sally

如果我编写如下方法:

@hug.get_post('/hello')
def hello (name: list)
   print(type(name))
   return name

然后单个参数变成一个字符列表。即['B', 'o', 'b']name但是如果参数有多个实例(例如['Bob', 'Sally']),这很好用

所以我现在解决它的方法是添加以下代码:

@hug.get_post('/hello')
def hello (name)
   names=list()
   if type(name) != 'list'
      names.append(name)
   else:
      names=name
   return names

这有效,但感觉不对。我认为有更好的方法可以做到这一点,但我目前无法弄清楚。

4

3 回答 3

1

如果你想更简洁,你可以像这样使用三元运算符:

@hug.get_post('/hello')
def hello (name)
   return name if isinstance(name, list) else [name]
于 2019-11-05T02:32:58.200 回答
1

Hug 为此提供了一种类型:hug.types.multiple

import hug
from hug.types import multiple

@hug.get()
def hello(name: multiple):
    print(type(name))

    return name

现在/hello?name=Bob返回['Bob']/hello?name=Bob&name=Sally返回['Bob', 'Sally']

如果要验证内部元素,可以创建一个自定义类型,如下所示:

import hug
from hug.types import Multiple, number

numbers = Multiple[number]()

@hug.get()
def hello(n: numbers):
    print(type(n))

    return n

在这种情况下/hello?n=1&n=2返回[1, 2]/hello?n=1&n=a导致错误:

{"errors": {"n": "提供的整数无效"}}

于 2019-11-05T02:46:55.830 回答
0

我不确定您是否可以以更优雅的方式做到这一点。

isinstance()是一种非常常见的检查类型的方法。下面的代码可以处理元组、列表或字符串

@hug.get_post('/hello')
def hello (name):
   if isinstance(name, (list, tuple)):
      names = name
   else:
      names = [name]      
   return names
于 2019-11-05T02:14:32.577 回答