Python 从html表单获取整数
我想从HTML表单中获取整数值,我使用了以下python代码:Python 从html表单获取整数,python,html,Python,Html,我想从HTML表单中获取整数值,我使用了以下python代码: form = cgi.FieldStorage() if not form.has_key("id"): error_pop("There is no id in this form","The format of the request is not correct") id = form["id"].value (*) 在HTML文件中,我将输入类型设置为number: id: &
form = cgi.FieldStorage()
if not form.has_key("id"):
error_pop("There is no id in this form","The format of the request is not correct")
id = form["id"].value (*)
在HTML文件中,我将输入类型设置为number
:
id: <input type="number" name="id" /><br />
实际上,如果我从error.log grep今天的时间,那么它就不能显示当前的错误..虽然它确实存在几个小时前发生的一些错误
我发现了一些新的东西:只有当事情涉及到“id”时,才会出现内部服务器错误。如果我执行类似于id=form[“idid”].value的操作,那么它将给出错误:
<type 'exceptions.TypeError'>: int() argument must be a string or a number, not 'NoneType'
args = ("int() argument must be a string or a number, not 'NoneType'",)
message = "int() argument must be a string or a number, not 'NoneType'"
:int()参数必须是字符串或数字,而不是“NoneType”
args=(“int()参数必须是字符串或数字,而不是'NoneType'”)
message=“int()参数必须是字符串或数字,而不是“NoneType”
非常感谢您的帮助。元素的值似乎是form
,您传递给int
的是http服务器返回的错误消息:
%d格式:需要数字,而不是str“
为了便于讨论,您是否可以在不将id字段限制为type=“number”,但type=“text”的情况下尝试相同的操作。我猜这将允许转换为整数。
如果需要将结果强制为整数,请使用
while not id:
try:
id = int(form["id"].value)
except TypeError:
error_pop("id should be number")
我遇到了和你一样的问题,无法将值从表单转换为数字。这是我改编的另一个解决方案。我从名为q1、q2、q3等单选按钮集返回了一些值,并使用此字典对它们进行转换
str2num = {"1":1, "2":2, "3":3, "4":4, "5":5, "6":6}
val1 = str2num[ form.getvalue("q1") ]
val2 = str2num[ form.getvalue("q2") ]
val3 = str2num[ form.getvalue("q3") ]
form元素“q1”的值是数字的字符串形式,因此这会将其转换为数字形式。像你一样,int(form.getvalue(“q1”)
就是不起作用。我还是不知道为什么会这样。嗨!你能发布你得到的错误吗?@Littm,你是指int(form[“id”].value)中的错误吗?虽然有数百行错误……您提到的错误:但是python给了我很多我看不懂的错误。
?@Littm,哈,我发现这数百行错误是因为我没有以正确的权限执行python文件,在添加sudo python xx.py之后,它工作了。但字符串问题仍然存在。从web浏览器端返回的错误是::%d格式:需要数字,而不是str args=('%d格式:需要数字,而不是str',)消息='%d格式:需要数字,而不是str'@Littm,如果我添加int(form[“id”].value),则服务器将返回内部服务器错误..谢谢您的回答!我试图通过增加一些额外的东西来达到目的。首先,我将id
设置为文本字段而不是数字,然后使用正则表达式搜索模式:m=re.search(“^(?P[-\d]+)$”,id)
然后我将其转换为整数:id=int(m.group('x')代码>它以某种方式工作,不会给我内部服务器错误。我不知道以前的内部服务器错误的原因以及为什么不能直接使用数字字段。。。
str2num = {"1":1, "2":2, "3":3, "4":4, "5":5, "6":6}
val1 = str2num[ form.getvalue("q1") ]
val2 = str2num[ form.getvalue("q2") ]
val3 = str2num[ form.getvalue("q3") ]