处理函数param,可以在Python中使用str或list
我不是一个有经验的Python程序员,但我觉得我对这个问题的解决方案不正确,我认为有一个更好的方法来处理Python中的这个问题 在本例中,这是在使用,但这可能基本上是不相关的 假设代码是这样的:处理函数param,可以在Python中使用str或list,python,hug,Python,Hug,我不是一个有经验的Python程序员,但我觉得我对这个问题的解决方案不正确,我认为有一个更好的方法来处理Python中的这个问题 在本例中,这是在使用,但这可能基本上是不相关的 假设代码是这样的: @hug.get_post('/hello') def hello (name) print(type(name)) return name import hug from hug.types import Multiple, number numbers = Multiple[num
@hug.get_post('/hello')
def hello (name)
print(type(name))
return name
import hug
from hug.types import Multiple, number
numbers = Multiple[number]()
@hug.get()
def hello(n: numbers):
print(type(n))
return n
当使用name
参数的一个实例发送请求时,hello
函数将获得一个str
-如下所示:
POST /hello?name=Bob
但是,如果请求被发送到多个name
参数,则该方法将接收字符串的列表,如中所示
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
这是可行的,但感觉不对。我认为有更好的方法可以做到这一点,但我现在还不清楚。我不确定你能不能用更优雅的方式来做到这一点
isinstance()
是检查类型的一种非常常见的方法。
下面的代码可以处理元组、列表或字符串
@hug.get_post('/hello')
def hello (name):
if isinstance(name, (list, tuple)):
names = name
else:
names = [name]
return names
如果您想更简洁,可以使用三元运算符,如下所示:
@hug.get_post('/hello')
def hello (name)
return name if isinstance(name, list) else [name]
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']
如果要验证内部元素,可以创建如下自定义类型:
@hug.get_post('/hello')
def hello (name)
print(type(name))
return name
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”:“提供的整数无效”}
这绝对不正确:如果类型(名称)!='列表“
type
的结果永远不会等于字符串type
返回一个类对象,因此如果type(name)不是list的话,您可以在这里使用,但是您应该使用isinstance
来获得更惯用的东西