我正在尝试从一个 Python 脚本生成的网页中获取用户输入的数据,以提交给另一个 Python 脚本来处理该数据。在第一个 python 脚本中,我使用以下内容创建了一个 Web 表单来提交数据:
print("<form action='newspeciescheck.py' method='post'>")
print("<p>Genus: <input type='text' name='newgenus'/> <p>Species: <input type='text' name='newspecies'/>")
print("<input type='submit' value='Enter'>")
print("</form>\n ")
在我的目标脚本中
formfields = cgi.FieldStorage()
newgenus = formfields.getValue('newgenus')
newspecies = formfields.getValue('newspecies')
但是,当我尝试运行它时,cgitb 抛出一个错误告诉我:
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
C:\Abyss Web Server\htdocs\pyscripts\newspeciescheck.py in ()
21
22 formfields = cgi.FieldStorage()
=> 23 newgenus = formfields.getValue('newgenus')
24 status=''
25 if newgenus==None:
newgenus undefined, formfields = FieldStorage(None, None, [MiniFieldStorage('newg...phis'), MiniFieldStorage('newspecies', 'fabae')]), formfields.getValue undefined
C:\Users\John\AppData\Local\Programs\Python\Python36\lib\cgi.py in __getattr__(self=FieldStorage(None, None, [MiniFieldStorage('newg...phis'), MiniFieldStorage('newspecies', 'fabae')]), name='getValue')
583 def __getattr__(self, name):
584 if name != 'value':
=> 585 raise AttributeError(name)
586 if self.file:
587 self.file.seek(0)
builtin AttributeError = <class 'AttributeError'>, name = 'getValue'
AttributeError: getValue
args = ('getValue',)
with_traceback = <built-in method with_traceback of AttributeError object>
那么,为什么我提交的值最终会出现在 MiniFieldStorage 而不是普通的 FieldStorage 中?更重要的是,我如何让它们像普通的 FieldStorage 一样结束?
请您参考如下方法:
您看到错误是因为您正在尝试访问 FieldStorage 的 getValue 方法,它没有一个 - 正确的方法名称是 getvalue - 注意小写的 v。
但是,这是您关于 FieldStorage 与 MiniFieldStorage 的问题的答案
根据documentation ,值最终是 FieldStorage 还是 MiniFieldStorage 实例取决于用于提交它们的表单的编码类型(enctype 属性)。
The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive multipart/* encoding). When this occurs, the item will be a dictionary-like FieldStorage item. This can be determined by testing its type attribute, which should be multipart/form-data (or perhaps another MIME type matching multipart/*). In this case, it can be iterated over recursively just like the top-level form object.
When a form is submitted in the “old” format (as the query string or as a single data part of type application/x-www-form-urlencoded), the items will actually be instances of the class MiniFieldStorage.
default encoding type是application/x-www-form-urlencoded 所以如果你想强制使用FieldStorage,你的表单声明需要是
<form action='newspeciescheck.py' method='post' enctype="multipart/form-data">
参见 this answer用于讨论表单编码,以及为什么您可以选择其中一个。
