如何修复:"TypeError: 'bool' object is not subscriptable"

3

我目前正在处理一个基本的客户端/服务器应用程序,并实现一个简单的RSA / 公钥身份验证系统。但是我遇到了这个错误,无论如何我都无法解决它。

我正在使用最新版本的Python。

server.py

def getUserData(username):
    global privateKeysFilename
    filename = privateKeysFilename

    with open(filename, "r") as keysFile:
        for line in keysFile:
            line = [token.rstrip("\n") for token in line.split(",")]
            if(username == line[0]):

                if DEBUG:
                    print("\n=== DEBUG\nUser data = %s\n===\n" %(line))

                return line
    return False



def running(self):
    global BUFFER, DEBUG, start, final

    while 1:
        print('Waiting for a connection')
        connection, client_address = self.server_socket.accept()
        connection.send("Successful connection!".encode())

        x = randint(start, final)
        self.fx = function(x)
        connection.send(str(x).encode())

        try:
            # Output that a client has connected
            print('connection from', client_address)
            write_connection()
            # Set the time that the client connected
            start_time = datetime.datetime.now()

            # Loop until the client disconnects from the server
            while 1:
                # Receive information from the client
                userData = connection.recv(BUFFER)

                #data = connection.recv(1024).decode()

                if(userData != "0"):

                    #define split character 
                    ch = ","

                    userData = userData.split(ch.encode())
                    username = userData[0]
                    r = int(userData[1])

                    userData = getUserData(username)

                    e, n = int(userData[1]), int(userData[2])
                    y = modularPower(r, e, n)

                    if DEBUG:
                        print("=== DEBUG\ne = %d\nn = %d\nr = %d\ny = %d\n===\n" %(e, n, r, y))

                    if(self.fx == y):
                        #if authentication passed
                        connection.send("Welcome!!!".encode())
                    else:
                        connection.send("Failure!!!".encode())



                if (userData != 'quit') and (userData != 'close'):
                    print('received "%s" ' % userData)
                    connection.send('Your request was successfully received!'.encode())
                    write_data(userData)
                    # Check the dictionary for the requested artist name
                    # If it exists, get all their songs and return them to the user
                    if userData in self.song_dictionary:
                        songs = ''
                        for i in range(len(self.song_dictionary.get(userData))):
                            songs += self.song_dictionary.get(userData)[i] + ', '
                        songs = songs[:-2]
                        print('sending data back to the client')
                        connection.send(songs.encode())
                        print("Sent", songs)
                    # If it doesn't exist return 'error' which tells the client that the artist does not exist
                    else:
                        print('sending data back to the client')
                        connection.send('error'.encode())
                else:
                    # Exit the while loop
                    break
            # Write how long the client was connected for
            write_disconnection(start_time)
        except socket.error:
            # Catch any errors and safely close the connection with the client
            print("There was an error with the connection, and it was forcibly closed.")
            write_disconnection(start_time)
            connection.close()
            data = ''
        finally:
            if data == 'close':
                print('Closing the connection and the server')
                # Close the connection
                connection.close()
                # Exit the main While loop, so the server does not listen for a new client
                break
            else:
                print('Closing the connection')
                # Close the connection
                connection.close()
                # The server continues to listen for a new client due to the While loop

这是带有错误输出的结果:


Traceback <most recent call last>:
    File "server.py", line 165, in running
    e, n = int(userData[1]), int(userData[2])
TypeError: 'bool' object is not subscriptable


任何帮助都会非常感激! :)

2
userData = getUserData(username)。getUserData(..) 很可能返回一个 bool 值。请检查该结果。 - han solo
1
请下次提供一个 [MCVE],你的代码基本没什么用处。 - Ocaso Protal
就像@han solo提到的那样,getUserData(..)很可能会返回一个布尔值。尝试打印userData并检查其值。 - David Sidarous
@han solo 感谢您的回复。是的,getUserData(username) 返回 false,但是当我删除 return 语句时,我得到了相同的 TypeError,不过错误信息变成了 'NoneType' object is not subscriptable - Dylan Freeman
@OcasoProtal 对不起,这是我第一次使用这个函数,我一定会记住的,谢谢。 - Dylan Freeman
1
@DylanFreeman 你应该返回两个值,因为你在执行 e, n = int(userData[1]), int(userData[2]) - han solo
1个回答

5
通过使用userData[n],您尝试访问可下标对象中的第n个元素。
这可以是一个listdicttuple甚至是一个string
您看到的错误意味着对象userData既不属于前面提到的类型,而且它是一个布尔值(TrueFalse)。
由于这是调用函数getUserData()的结果,建议您检查此函数的返回类型,并确保它是上述类型之一,并修改代码逻辑。
[更新]
通过检查函数getUserData(),发现它仅在包含用户名的情况下返回行,否则会返回False,而主代码没有处理它。
我建议将以下成功状态包括在返回值中。
def getUserData(username):
    global privateKeysFilename
    filename = privateKeysFilename

    with open(filename, "r") as keysFile:
        for line in keysFile:
            line = [token.rstrip("\n") for token in line.split(",")]
            if(username == line[0]):

                if DEBUG:
                    print("\n=== DEBUG\nUser data = %s\n===\n" %(line))

                return True, line
    return False, None

在您的代码中调用getUserData()时,首先要检查是否成功,然后再像这样解析数据

userData = getUserData(username)
if userData [0]:
    e, n = int(userData[1]), int(userData[2])
    y = modularPower(r, e, n)
else:
    # Your failure condition

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