【问题标题】:get integer from html form从html表单获取整数
【发布时间】:2015-11-23 12:01:26
【问题描述】:

我想从 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: <input type="number" name="id" /><br />

但是,我从行 (*) 获得的 id 似乎仍然是一个字符串。

如何将其转换为整数?

我尝试使用int(form["id"].value),但python给了我以下错误:

&lt;type 'exceptions.TypeError'&gt;: %d 格式: 需要一个数字, 不是 str args = ('%d 格式: 需要一个数字, 不是 str',) message = '%d 格式: 需要一个数字, 不是 str '

所以,我放弃了使用int()

如果我在将其解析为int() 之前尝试打印该值,那么我将从浏览器收到内部服务器错误。实际上,如果我更改 python 文件中的某些内容,我总是会收到此错误。我可以从 error_log.log 中看到错误:

/usr/lib/python2.6/cgitb.py:173: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
value = pydoc.html.repr(getattr(evalue, name))

实际上,如果我从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'"

感谢任何帮助。

【问题讨论】:

  • 嗨!你能发布你得到的错误吗?
  • @Littm,您的意思是来自 int(form["id"].value) 的错误?虽然有数百行错误...
  • 你提到的错误:but python gave me tons of errors that I cannot read ?
  • @Littm,哈,我发现有几百行错误是因为我没有以正确的权限执行python文件,添加sudo python xx.py后,它可以工作。但是字符串问题仍然存在。浏览器端返回的错误是:: %d format: a number is required, not str args = ('%d format: a number is required, not str',) message = ' %d 格式:需要一个数字,而不是 str'
  • @Littm,如果我添加 int(form["id"].value),那么服务器将返回内部服务器错误..

标签: python html


【解决方案1】:

我遇到了同样的问题,无法将值从表单转换为数字。这是我改编自this blog post 的另一个解决方案。我有一些从名为 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") ]

表单元素“q1”的值是数字的字符串形式,因此将其转换为数字形式。像你一样,int( form.getvalue("q1") ) 只是没有工作。我仍然不知道为什么会这样。

【讨论】:

    【解决方案2】:

    似乎元素的值是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")
    

    【讨论】:

    • 感谢您的回答!我试图通过添加一些额外的东西来实现它。首先,我将id 设为文本字段而不是数字,然后我使用正则表达式来搜索模式:m = re.search("^(?P&lt;x&gt;[-\d]+)$", id); 然后我将其转换为整数:id = int(m.group('x')); 它以某种方式工作并且没有给我内部服务器错误。我不知道以前内部服务器错误的原因以及为什么不能直接使用数字字段...
    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2017-07-22
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多