HTML input array parsing in Python (GAE)

2019-02-20 19:58发布

I'm two days in to Python and GAE, thanks in advance for the help.

I have an input array in HTML like this:

<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">

I want to parse the input in Python, and I'm trying this, which isn't working:

items = self.request.get('p_item')
for n in range(1,len(items)):
  self.response.out.write('Item '+n+': '+items[n])

What is the correct way to do this?

2条回答
祖国的老花朵
2楼-- · 2019-02-20 20:46

Change your html to this

<input type="text" name="p_item">
<input type="text" name="p_item">
<input type="text" name="p_item">

and use the self.request.get_all() method http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_get_all

p.s. For reference, there is no concept of arrays for GET/POST data, your form gets transformed a key=value string separated by '&' e.g.

p_item=1&p_item=3&p_item=15

etc, it's up to the web framework to interpret whether a parameter is an array.

Edit: oops, just read the comments that you figured this out already, oh well :P

查看更多
Deceive 欺骗
3楼-- · 2019-02-20 20:51

I would recommend doing some debugging if this sort of issue comes up. Make things simple and write out your variable values and ensure you get what you expect at each step. Do something like the following:

<form method="get">
   <input type="text" name="single_key" />
   <input type="text" name="array_key[some_key]" />
   <input type="submit" />
</form>

And see what happens when running the following Python on the backend:

single_value = self.request.get('single_key')
self.response.out.write(str(single_value))

array_value = self.request.get('array_key')
self.response.out.write(str(array_value))

Based on the output you should have a better idea of what to get the desired results or how to add more detail to your question if you still don't understand a certain behavior.

查看更多
登录 后发表回答