【问题标题】:Python cgi.FieldStorage() is empty on form submissionPython cgi.FieldStorage() 在表单提交时为空
【发布时间】:2014-05-31 20:18:33
【问题描述】:

我的 Apache 2 虚拟主机配置中有以下指令:

<Directory /var/www/foo_test>
  Options MultiViews +ExecCGI
  AddHandler cgi-script .py
  AllowOverride All 
</Directory>

我有以下简单的 HTML 表单:

<html>
  <body>
    <form action="foo.py" method="post" id="foo_form">
      <input type="text" id="foo" />
      <input type="submit" />
    </form>
  </body>
</html>

这里是foo.py,表单提交时调用的可执行脚本:

#!/usr/bin/env python

import cgi
arguments = cgi.FieldStorage()

print "Content-Type: text/html\n"
print repr(arguments)

当我提交表单时,我收到以下回复:

FieldStorage(None, None, [])

FieldStorage 对象实例中没有任何内容包含以 foo_form 形式指定的字段的值。

如果我将 Python 脚本替换为 Perl 脚本及其 CGI 模块,同时更改 Apache 指令以处理 Perl CGI,我可以毫无问题地从表单中读取字段。这表明我的 Apache 设置没问题。

但是,我是否在实例化 cgi.FieldStorage() 对象或我的 Apache 设置时遗漏了一些导致表单提交失败的内容?

【问题讨论】:

    标签: python apache2 cgi


    【解决方案1】:

    如果你想在表单中提交数据,你需要给输入一个name属性。

    【讨论】:

      【解决方案2】:

      这让我大吃一惊,但这就是发生在我身上的事情。

      显然你不能多次从cgi.FieldStorage“拉”信息?

      从浏览器中的任何console 选项卡运行:

      $.post('/api/save.cgi', {'hello': 'world'}, (response) => {
         console.log("DONE");
      });
      

      后端的 Python 代码

      #!/usr/bin/env python3
      
      import cgi
      
      fcgi = cgi.FieldStorage()
      sys.stderr.write("try 1 %s \n" % fcgi)
      
      fcgi = cgi.FieldStorage()
      sys.stderr.write("try 2: %s \n" % fcgi)
      

      查看错误日志:

      try 1: FieldStorage(None, None, [MiniFieldStorage('hello', 'world')])
      try 2: FieldStorage(None, None, [])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        • 1970-01-01
        • 2010-11-19
        相关资源
        最近更新 更多