我已经编写了一个非常基本的Python Web服务器,并正在使用Web浏览器对其进行测试。
我可以使用以下方法连接并加载页面:
localhost:8080/index.htm
我也有一个默认的404 Not Found
htm页面,当输入其他一些单词而不是时会加载该页面index.htm
。
但是,当没有页面键入时,如下所示:localhost:8080
我希望为此也加载index.htm,但它无法识别没有文件名的事实。这是我的代码:
essage = connectionSocket.recv(1024)
print("The client request message is: %s" % message)
filename = message.split()[1]
print("filename is %s" % filename[0:])
try:
if not filename:
print("not filename")
filename = "/index.htm"
f = open(filename[1:])
outputdata = f.read(1024)
okmessage = "HTTP/1.1 200 OK"
except OSError:
print ("There was an OSError")
这是当我在localhost:8080
Web浏览器中键入时的输出:(它应该加载index.htm页面)
Got a connection from ('192.168.1.9', 51453)
This request is served by thread 4568
The client request message is: b'GET / HTTP/1.1\r\nHost: 192.168.1.9:8080\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n\r\n'
filename is b'/'
There was an OSError
在localhost:8080/index.htm
浏览器中键入时,输出为:
This request is served by thread 4568
The client request message is: b'GET /index.htm HTTP/1.1\r\nHost: 192.168.1.9:8080\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n\r\n'
filename is b'/index.htm'
我将文件名上的print语句更改为,print("filename is %s" % filename[0:])
而不是,print("filename is %s" % filename[1:])
现在您可以看到,当没有在浏览器中键入文件名时,它会打印出一个文件名,b'/'
因此计算结果为true?
我正在Windows 7机器上运行它。预先感谢您的帮助。
每个@ n9code更新
问题出在以下代码中:
if filename == '':
filename = "index.htm"
f = open(filename[1:])
如果您要求提供一个文件名(如)localhost:8080/filename.html
,则会得到filename == '/filename.html'
,然后使用来访问您的文件名filename[1:]
。一切都很好,但是当您检测到请求中未提供文件名时,您可以手动为filename
变量分配值"index.html"
,然后在filename[1:]
获取时"ndex.html"
不存在该值。
因此,解决您的问题的方法可能是更改代码,如下所示:
if not filename or filename == b'/':
filename = "/index.htm"
f = open(filename[1:])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句