我寫了一個非常基本的Python Web服務器,並使用Web瀏覽器進行測試。python web服務器如何識別url中沒有文件名?
我可以連接並使用加載頁面:
localhost:8080/index.htm
我也有當一些換句話說被輸入,而不是index.htm
加載默認404 Not Found
的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機器上運行這個。預先感謝您的幫助。每@
UPDATE n9code
在Python 3,socket.recv'的'返回值是一個字節的對象,而不是字符串。 'b''=='''產生'False'。 – nymk