python - 如何修复:“TypeError:'bool' 对象不可下标”
问题描述
我目前正在使用一个基本的客户端/服务器应用程序并实现一个简单的 RSA/公钥认证系统。我遇到了这个错误,我一生都无法弄清楚。
我正在使用最新版本的python。
服务器.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
任何帮助将不胜感激!:)
解决方案
通过使用userData[n]
,您正在尝试访问可下标对象中的第 n 个元素。
这可以是list
, dict
,tuple
甚至是string
.
您看到的错误意味着您的对象userData
既不是前面提到的类型,它是一个布尔(True
或False
)
既然是调用函数的结果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
推荐阅读
- g++ - 在 Windows 上使用“make”和“g++”或如何让 karambola 在 Windows 上工作
- pyton-couchdb - 由于某种原因需要此代码的帮助,它使用函数不断打印无矩形图案
- ios - 在没有第三方库的情况下确定 iOS 14 Swift 5 中的网络类型
- java - 与元素类型“ApplicationName”关联的属性“Application Version”应为开放式报价
- r - r API GET、PUT、DELTE 循环应用
- javascript - 在 Safari 中提交表单之前更改元素可见性有时不起作用
- c++ - 有没有办法在 C++ 中识别重载运算符 [] 的类?
- apache-spark - 使用 .mani/ 清单文件读取分桶目录
- python - IMAP 搜索查询中有多少次重叠
- php - 有没有更有效的编码方式(没有 mysql )