문제

Using webapp2 I create unit tests for a form where there are checkboxes for votes so multiple values can be posted for the vote field and they are retrieved via request.POST.getall('vote'):

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

In the unit test I tried passing a list:

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

But looks like it's simply converted to a string:

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

How can I pass multiple values for vote that will be retrieved as a list via request.POST.getall()?

도움이 되었습니까?

해결책

POST data is encoded using query string encoding, and multiple items by the same name are represented by repeating the key with different values. For instance:

vote=Better&vote=Faster&vote=Stronger

Python has library functions to do this for you, though:

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

The second argument (True) to urlencode is called 'doseq', and instructs urlencode to encode sequences as lists of separate elements.

다른 팁

The webtest library is helpful for these test cases.

http://webtest.pythonpaste.org/en/latest/index.html#form-submissions

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top