python - TypeError:str() 最多接受 1 个参数(给定 2 个)并且 TypeError:需要一个整数
问题描述
我正在尝试通过http://myipaddr:50997/notExisted.html访问不存在的文件类型, 但出现以下错误。有人可以向我解释吗?
from socket import *
serverPort = 50997
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print ("Ready to serve...")
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
try:
# Receives the request message from the client
message = connectionSocket.recv(1024)
print ("Message is: "), message
filename = message.split()[1]
print ("File name is: "), filename
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
# Close the client connection socket
connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
我得到的错误。
connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
TypeError: str() takes at most 1 argument (2 given)
当我尝试删除 bytes(); 时出现此错误
Traceback (most recent call last):
File "tcpServer.py", line 26, in <module>
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8")
TypeError: an integer is required
解决方案
需要整数的错误消息有点令人困惑,因为您可以.send()
使用bytes
参数调用,因此您走在了正确的轨道上。
但是,您调用bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8")
, 即带有两个参数。您不需要为bytes()
演员提供编码,bytes("HTTP/1.1 404 Not Found\r\n\r\n")
就足够了。
如果要指定编码,请改用:
"HTTP/1.1 404 Not Found\r\n\r\n".encode('UTF-8')
IE:
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode("UTF-8"))
推荐阅读
- mongodb - Django rest 框架 serializer.save() 不保存到数据库并显示 ConnectionAbortedError:
- database-partitioning - 我们如何在 ODI 12c 中对数据进行分区?
- gnuplot - 来自数据文件的 gnuplot splot - 理解数据对齐
- python - 如何在 Python(Selenium) 中单击此 HTML 元素
- java - AES/GCM/NoPadding 从节点加密并在 java 上解密,抛出 AEADBadTagException: Tag mismatch
- firebase - Flutter,与两个不同的应用程序聊天
- javascript - 使用js根据fps更改文件名
- javascript - 反应中带有 JSX.Element 的 TypeScript 类型将不接受 .map() 并给出错误 TS2339
- json - 我正在尝试将 Jolt 变换用于以下嵌套结构
- numpy - 无法从不同 conda env 的站点包中导入 NumPy