python - 列表索引超出范围防止 404 错误?
问题描述
我正在尝试完成此实验,但似乎无法使其正常工作。当我尝试获取服务器不存在的文件时,我得到了
此页面无法正常工作 127.0.0.1 发送了无效响应。ERR_INVALID_HTTP_RESPONSE
我想得到的回应是
404 找不到文件
当我尝试加载不存在的文件时,编译器会在第 16 行显示:
文件名 = message.split()[1] IndexError: 列表索引超出范围
代码编译,我可以打开我的 Hello World 文件,但我无法得到这个 404 错误。我得到了一个框架代码,所以有些事情我无法在不偏离课程材料的情况下进行更改。
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a server socket
serverPort = 7000
serverSocket.bind(('127.0.0.1', serverPort))
serverSocket.listen(5)
while True:
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
#Fill in start #Fill in end
try:
message = connectionSocket.recv(1024)
print (message)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
#Fill in start
connectionSocket.send('\nHTTP/1.x 200 OK\n'.encode())
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
print ('File Recieved')
except IOError:
connectionSocket.send('\n404 File Not Found\n'.encode())
connectionSocket.close()
#Close client socket
serverSocket.close()
sys.exit()
骨架代码似乎是 Python 2,我使用的是 Python 3。我做了一些小的语法调整来调整。
删除 print(message) 会在编译器中产生“File Recieved”,但浏览器中仍然没有 404 错误。8小时后我不知所措。
解决方案
IndexError
处理in的一种方法message.split()[1]
是处理 and IndexError
in message.split()[1]
;)
try:
filename = message.split()[1]
except IndexError:
send_404_response()
continue
推荐阅读
- wordpress - 如何输出 ACF 自定义字段代替 WordPress 特色图片
- reactjs - 从父级到子级的状态更改未反映到 React Hook 中的 TextField
- polygon - Catias 3dxml 格式是否包含作为 Nurbs 的 CAD,或者它只是一个三角形/多边形网格?
- react-native - 删除标题特定页面
- ubuntu - VS 代码不再打开
- python - 如何使用 BeautifulSoup 和 Selenium 实现 if 语句
- c - 需要了解C中的一些指针
- dgraph - Dgraph:在您的 Golang 结构字段中始终使用 omitempty 是最佳实践吗?
- oop - 对应用设计模式感到困惑
- sql - 如何在oracle sql查询中提取括号之间有几行的字符串