2009-06-03 26 views
5

我已經找到了用Python編寫的,一個非常簡單的HTTP服務器,它是do_get方法是這樣的:自定義簡單的Python HTTP服務器不服務CSS文件

def do_GET(self): 
     try: 
      self.send_response(200) 
      self.send_header('Content-type', 'text/html') 
      self.end_headers(); 
      filepath = self.path 
      print filepath, USTAW['rootwww'] 

      f = file("./www" + filepath) 
      s = f.readline(); 
      while s != "": 
       self.wfile.write(s); 
       s = f.readline(); 
      return 

     except IOError: 
      self.send_error(404,'File Not Found: %s ' % filepath) 

它工作正常,除了一個事實 - 這是不提供任何css文件(它沒有css呈現)。任何人都有這個問題的建議/解決方案?

最好的問候, praavDa

+0

快速建議:Google cherrypy。 – Triptych 2009-06-03 21:45:28

+0

**警告舊線程**嘗試將.css文件存儲在您的html文件所在的同一目錄中。 – noobninja 2016-04-02 08:03:53

回答

6

這似乎是返回的HTML的MIME類型的所有文件:

self.send_header('Content-type', 'text/html') 

而且,它似乎是相當糟糕的。你爲什麼對這個糟糕的服務器感興趣?看看cherrypy或粘貼好HTTP服務器的python實現和一個好的代碼來學習。


編輯:試圖修復它爲您提供:

import os 
import mimetypes 

#... 

    def do_GET(self): 
     try: 

      filepath = self.path 
      print filepath, USTAW['rootwww'] 

      f = open(os.path.join('.', 'www', filepath)) 

     except IOError: 
      self.send_error(404,'File Not Found: %s ' % filepath) 

     else: 
      self.send_response(200) 
      mimetype, _ = mimetypes.guess_type(filepath) 
      self.send_header('Content-type', mimetype) 
      self.end_headers() 
      for s in f: 
       self.wfile.write(s) 
+3

我使用這個很爛的,因爲它是我的項目的主題 - 我需要在python中編寫http服務器。感謝您的迴應。 – praavDa 2009-06-04 03:00:19

9

你明確地服務於所有文件爲Content-type: text/html,在這裏您要爲CSS文件作爲Content-type: text/css。有關詳細信息,請參見this page on the CSS-Discuss Wiki。 Web服務器通常有一個查找表,用於將文件擴展名映射到Content-Type。

+3

在python模塊mimetypes有查找表 – 2009-06-03 21:57:11