为什么web窗体将字段作为MiniFieldStorage返回给PythonCGI?

2024-10-01 04:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个Python脚本生成的web页面中获取用户输入的数据,然后提交给另一个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 ")

在我的目标脚本中

^{pr2}$

但是,当我尝试运行这个时,cgib抛出一个错误,告诉我:

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中?更重要的是,如何让它们最终成为普通的现场存储?在


Tags: 数据nameinpyself脚本noneinput
1条回答
网友
1楼 · 发布于 2024-10-01 04:53:21

您看到错误是因为您试图访问FieldStoragegetValue方法,但它没有一个-正确的方法名是getvalue-注意小写的v

但是,这是您关于FieldStoragevsMiniFieldStorage问题的答案

根据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 typeapplication/x-www-form-urlencoded,因此如果您想强制使用FieldStorage,那么表单声明必须是

<form action='newspeciescheck.py' method='post' enctype="multipart/form-data">

请参见this answer以了解有关表单编码的讨论,以及为什么要选择其中之一。在

相关问题 更多 >