我不是一个经验丰富的Python程序员,但我觉得我对这个问题的解决方案是不正确的,我认为在Python中有更好的方法来解决这个问题。
在这种情况下,这是使用拥抱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
这很管用,但感觉不对。我认为有更好的方法来做这件事,但我目前还不明白。
发布于 2019-11-04 18:46:55
拥抱提供了一种类型: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
将导致错误:
{“错误”:{"n":“提供的无效整数”}}
发布于 2019-11-04 18:32:58
如果您想要更简洁,可以使用如下三元运算符:
@hug.get_post('/hello')
def hello (name)
return name if isinstance(name, list) else [name]
发布于 2019-11-04 18:14:32
我不确定你能不能做一件更优雅的事情。
isinstance()
是一种非常常见的检查类型的方法。下面的代码可以处理元组、列表或字符串
@hug.get_post('/hello')
def hello (name):
if isinstance(name, (list, tuple)):
names = name
else:
names = [name]
return names
https://stackoverflow.com/questions/58703401
复制