2010-07-20 65 views
2

我正在編寫一個非常基本的網絡服務器(當然,嘗試),雖然它現在提供HTML罰款,但我的CSS文件似乎完全不被識別。我的機器上也運行了Apache2,並且當我將文件複製到docroot時,頁面正確地被傳送。我也檢查了權限,他們似乎很好。這裏是我到目前爲止的代碼:BaseHTTPServer無法識別CSS文件

class MyHandler(BaseHTTPRequestHandler): 
    def do_GET(self): 
      try: 
       if self.path == "/": 
        self.path = "/index.html" 
       if self.path == "favico.ico": 
        return 
       if self.path.endswith(".html"): 
        f = open(curdir+sep+self.path) 
        self.send_response(200) 
        self.send_header('Content-type', 'text/html') 
        self.end_headers() 
        self.wfile.write(f.read()) 
        f.close() 
        return 
       return 
      except IOError: 
       self.send_error(404) 
     def do_POST(self): 
      ... 

爲了提供CSS文件,我需要做些什麼嗎?

謝謝!

回答

6

你可以添加到您的if語句

  elif self.path.endswith(".css"): 
       f = open(curdir+sep+self.path) 
       self.send_response(200) 
       self.send_header('Content-type', 'text/css') 
       self.end_headers() 
       self.wfile.write(f.read()) 
       f.close() 
       return 

或者

import os 
from mimetypes import types_map 
class MyHandler(BaseHTTPRequestHandler): 
    def do_GET(self): 
     try: 
      if self.path == "/": 
       self.path = "/index.html" 
      if self.path == "favico.ico": 
       return 
      fname,ext = os.path.splitext(self.path) 
      if ext in (".html", ".css"): 
       with open(os.path.join(curdir,self.path)) as f: 
        self.send_response(200) 
        self.send_header('Content-type', types_map[ext]) 
        self.end_headers() 
        self.wfile.write(f.read()) 
      return 
     except IOError: 
      self.send_error(404) 
+0

謝謝!我想這是這樣的,但不知道我是否需要一個單獨的案例。添加了這個,它像一個魅力工作! – tparrott 2010-07-20 14:57:37

+0

這對我來說是非常有啓發性的代碼 - 謝謝,gnibbler。一個小問題:至少在python 2.7中,它是mimetypes.types_map(複數),而不是.type_map – mikeh 2010-09-22 21:29:14

+0

@mikeh,謝謝我修復了它 – 2010-09-22 22:19:35

0

您需要添加一個處理css文件的案例。嘗試改變:

if self.path.endswith(".html") or self.path.endswith(".css"): 
+0

那麼,你可能會想將其添加爲一個獨立的情況下 - 你」我們希望爲CSS設置不同的Content-Type。但是這應該讓你開始。 – bstpierre 2010-07-20 14:47:51

+0

感謝您的回覆。我最終添加了一個單獨的案例,它的工作就像一個魅力。 – tparrott 2010-07-20 14:57:56