gpt4 book ai didi

python - 如何在 webapp2 下对具有相同名称的多个复选框的发布请求进行单元测试

转载 作者:太空狗 更新时间:2023-10-30 02:49:37 26 4
gpt4 key购买 nike

我使用 webapp2 为表单创建单元测试,其中有投票复选框,因此可以为 vote 字段发布多个值,并通过 request.POST.getall('投票'):

<input type="checkbox" name="vote" value="Better">
<input type="checkbox" name="vote" value="Faster">
<input type="checkbox" name="vote" value="Stronger">

在单元测试中我尝试传递一个列表:

response = app.get_response('/vote',
POST={'vote': [u'Better', u'Faster', u'Stronger']},
headers=[('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')]
)

但看起来它只是简单地转换为字符串:

votes = self.request.POST.getall('vote')
# => [u"[u'Better', u'Faster', u'Stronger']"]

如何为 vote 传递多个值,这些值将通过 request.POST.getall() 作为列表检索?

最佳答案

POST 数据使用query string encoding 进行编码,同名的多个item 通过重复不同值的key 来表示。例如:

vote=Better&vote=Faster&vote=Stronger

不过,Python 有库函数可以为你做这件事:

urllib.urlencode({
'vote': ['Better', 'Faster', 'Stronger'],
}, True)

urlencode 的第二个参数 (True) 称为“doseq”,指示 urlencode 将序列编码为单独元素的列表。

关于python - 如何在 webapp2 下对具有相同名称的多个复选框的发布请求进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7313124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com