简体   繁体   English

Python列表对象在通过CGI发送时作为文本字符串到达

[英]Python list object arrives as a text string when sent via CGI

I have a list object that I'm sending to a script using CGI. 我有一个列表对象,我正在使用CGI发送到脚本。 The list is being sent using a hidden field in an HTML form. 该列表使用HTML表单中的隐藏字段发送。 When I extract the object in the receiving script using my_list = form.getlist['name_of_hidden_field'], the list is stored as a single large text string in the first element of my_list rather than the list I want. 当我使用my_list = form.getlist ['name_of_hidden_​​field']在接收脚本中提取对象时,列表将作为单个大文本字符串存储在my_list的第一个元素中,而不是我想要的列表中。 What am I doing wrong? 我究竟做错了什么?

# snippet of code from the script with the HTML
my_list = ['string1', 'string2', 'string3]
print '<form name="input" action="my_script.py">'
print '<input type="hidden" name="my_list" value="%s">' % (my_list,)
print '<input type="submit" name="submit" value="Submit" />'
print "</form>"

# snippet of code from my_script.py
my_list = form.getlist('my_list')

# what I'm seeing in my_script.py
>>>print my_list
["['string1', 'string2', 'string3']"]

Thanks for your advice. 谢谢你的建议。

You need to send the list as a bunch of different input s with the same name for getlist to get the elements: 您需要将列表作为一组具有相同名称的不同input发送到getlist以获取元素:

my_list = ['string1', 'string2', 'string3']
print '<form name="input" action="my_script.py">'
for element in my_list:
    print '<input type="hidden" name="my_list" value="%s">' % (cgi.escape(element),)
print '<input type="submit" name="submit" value="Submit" />'
print "</form>"

Sending it via CGI will turn the list into a string. 通过CGI发送它会将列表转换为字符串。

To convert it back use: 要将其转换回来使用:

import ast

my_list = "['string1', 'string2', 'string3']"
my_new_list = ast.literal_eval(my_list)
print my_new_list 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM