开发者

Pylons formencode - How do I POST an array of data?

开发者 https://www.devze.com 2023-01-10 10:03 出处:网络
I have a form that is similar to the following: Enter Name: Enter Age: [add more] That add more field copies the Name a开发者_如何学Cnd Age inputs and can be clicked as many times as the user wants

I have a form that is similar to the following:

Enter Name:
Enter Age:
[add more]

That add more field copies the Name a开发者_如何学Cnd Age inputs and can be clicked as many times as the user wants. Potentially, they could end up submitting 50 sets of Name and Age data.

How can I handle this received data when it's posted to my Pylons application? I basically need to do something like:

for name, age in postedform:
   print name + ' ' + age

I've come across formencode's variabledecode function. But can't for the life of me figure out how to use it :/

Cheers.


You would post something like this (URL encoded, of course)

users-0.name=John
users-0.age=21
users-1.name=Mike
users-1.age=30
...

Do that for users 0-N where N is as many users as you have, zero-indexed. Then, on the Python side after you run this through variabledecode, you'll have:

users = UserSchema.to_python(request.POST)
print users

# prints this:
{'Users': [{'name': 'John', 'age': '21'}, {'name': 'Mike', 'age': '30'}]}

The values may differ depending on the validation you have going on in your schema. So to get what you're looking for, you would then do:

for user in users.iteritems():
  print "{name} {age}".format(**user)

Update

To embed a list within an dictionary, you would do this:

users-0.name=John
users-0.age=21
users-0.hobbies-0=snorkeling
users-0.hobbies-1=billiards
users-1.name=Mike
...

So on and so forth. The pattern basically repeats itself: {name-N} will embed the Nth index in a list, starting with 0. Be sure that it starts with 0 and that the values are consecutive. A . starts the beginning of a property, which can be a scalar, a list, or a dictionary.

This is Pylons-specific documentation of how to use formencode, look at table 6-3 for an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号