类型错误:第一个参数必须是字符串或只读字符缓冲区,而不是None。

4

我正在从HTML文件中获取值,但是遇到了TracebackError错误:我不知道应该怎么改变?

Traceback (most recent call last):
  File "test.py", line 33, in <module>
    get_data()
  File "test.py", line 25, in get_data
    f.write(form.getvalue('firstname'))
TypeError: argument 1 must be string or read-only character buffer, not None

我的Python代码:

# !/usr/bin/python
import cgi

def get_data():
    '''
    This function writes the HTML data into the file 

    '''

    print "Content- type : text/html\n"

    form = cgi.FieldStorage()

    #Fname = form.getvalue('firstname')
    #Lname = form.getvalue('lastname')
   #Age = form.getvalue('age')
   #Gender = form.getvalue('gender')

    f = open("abc.txt","w")

    f.write(form.getvalue('firstname'))
    f.write(form.getvalue('lastname'))
    f.write(form.getvalue('age'))
    f.write(form.getvalue('gender'))
    f.close()

#print "Hello ", Fname, Lname, Age, Gender

get_data()

我是一名新手,无法找到错误。请帮我解决。
HTML文件:
<html>
<head>
<title>INFORMATION</title>
</head>
<body>
 <form action = "/cgi-bin/test.py" method = "post">
FirstName:
<input type = "text" name = "firstname" /><br>
LastName:
<input type = "text" name = "lastname" /><br>
Age:
<input type = "text" name = "age" /><br>
Gender:
<input type="radio" name="gender" value="male" /> Male
<input type="radio" name="gender" value="female" /> Female

<input type = "submit" name = "submit "value = "SUBMIT">
<input type = "reset" name = "reset" value = "RESET">
 </form>
</body>
</html>

这不是你的问题,但值得注意的是最好使用with语句来处理文件。 - Gareth Latty
似乎“firstname”字段为空或缺失。你能展示一下生成要提交的表单的HTML吗? - Daniel Roseman
@Lattyware 他正在使用Python 2.6(来自之前的问题),无法使用with - Games Brainiac
form.getvalue('firstname')None。很可能是没有从 FieldStorage 中获取到值。 - thefourtheye
@GamesBrainiac,with和上下文管理器在2.5中被添加,如果你使用from __future__ import with_statement,而在2.6中则默认可用。 - Gareth Latty
请修复缩进。在Python中,这非常重要。 - Francesco Montesano
1个回答

1

form.getvalue('firstname') 返回的是None,而不是你期望的字符串,这就是为什么出现错误的原因。


好的。我正在填写表格,点击提交按钮却没有反应。 - john john
@johnjohn 那就是另一个问题了。问题在于,根据你所提供的信息,我们发现你得到了一个 None,但我们并不知道 form.getValue() 函数返回的是什么类型的值。 - Games Brainiac
但是当使用打印功能时,在提交按钮上显示正常。当写入文件时,会显示错误。 - john john

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接