2015-06-20 94 views
1

我寫了一個非常基本的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

+0

在Python 3,socket.recv'的'返回值是一個字節的對象,而不是字符串。 'b''=='''產生'False'。 – nymk

回答

0

的問題是在此代碼:

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:]) 
+0

謝謝你的幫助。這似乎並不奏效。它仍然認爲文件名是'b''',甚至沒有輸入'if not filename'語句。我在if語句中用print語句檢查了這一點。還有什麼你能想到的? –

+0

當你得到文件名值'b'''時,它是一個空字節數組,它的布爾值是'False'。因此,在這種情況下'not filename'必須是'True',並且執行必須進入'if'塊。你可以在你的代碼中添加更多'print',並且測試兩個文件名是否存在?然後在您的問題中發佈'print'輸出,以便我們可以進一步分析。 – bagrat

+0

我更新了問題。謝謝。 –

相關問題