2012-10-18 37 views
13

我喜歡用Python的SimpleHTTPServer各類Web應用程序需要加載資源。當我在網址中使用查詢字符串通過Ajax調用等爲什麼SimpleHTTPServer重定向到?查詢字符串/當我請求?查詢字符串?

的地方發展,服務器始終重定向到相同的URL以斜槓追加。

例如/folder/?id=1使用HTTP 301響應重定向到/folder/?id=1/

我只是使用python -m SimpleHTTPServer啓動服務器。

任何想法,我怎麼能擺脫重定向行爲?這是Python 2.7.2。

+0

SimpleHTTPServer僅提供文件。使用其他的東西來處理請求中的參數。 –

回答

3

好的。在Morten的幫助下,我想到了這一點,這似乎是我需要的一切:只要忽略查詢字符串(如果它們在那裏並提供靜態文件)。

import SimpleHTTPServer 
import SocketServer 

PORT = 8000 


class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 

    def __init__(self, req, client_addr, server): 
     SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, req, client_addr, server) 

    def do_GET(self): 
     # cut off a query string 
     if '?' in self.path: 
      self.path = self.path.split('?')[0] 
     SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) 


class MyTCPServer(SocketServer.ThreadingTCPServer): 
    allow_reuse_address = True 

if __name__ == '__main__': 
    httpd = MyTCPServer(('localhost', PORT), CustomHandler) 
    httpd.allow_reuse_address = True 
    print "Serving at port", PORT 
    httpd.serve_forever() 
+0

這似乎並不尊重url參數。它仍然在查詢參數後附加'/'。 –

2

我不確定重定向是如何生成的......我試過實現一個非常基本的SimpleHTTPServer,並且在使用查詢字符串參數時沒有得到任何重定向。

只需執行類似self.path.split("/")的操作並在處理請求之前處理路徑? 此代碼,你想要做什麼,我認爲:

import SocketServer 
import SimpleHTTPServer 
import os 


class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 
    def folder(self): 
     fid = self.uri[-1].split("?id=")[-1].rstrip() 
     return "FOLDER ID: %s" % fid 

    def get_static_content(self): 
     # set default root to cwd 
     root = os.getcwd() 
     # look up routes and set root directory accordingly 
     for pattern, rootdir in ROUTES: 
      if path.startswith(pattern): 
       # found match! 
       path = path[len(pattern):] # consume path up to pattern len 
       root = rootdir 
       break 
     # normalize path and prepend root directory 
     path = path.split('?',1)[0] 
     path = path.split('#',1)[0] 
     path = posixpath.normpath(urllib.unquote(path)) 
     words = path.split('/') 
     words = filter(None, words) 
     path = root 
     for word in words: 
      drive, word = os.path.splitdrive(word) 
      head, word = os.path.split(word) 
      if word in (os.curdir, os.pardir): 
       continue 
      path = os.path.join(path, word) 
      return path 

    def do_GET(self): 
     path = self.path 
     self.uri = path.split("/")[1:] 

     actions = { 
      "folder": self.folder, 
     } 
     resource = self.uri[0] 
     if not resource: 
      return self.get_static_content() 
     action = actions.get(resource) 
     if action: 
      print "action from looking up '%s' is:" % resource, action 
      return self.wfile.write(action()) 
     SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) 


class MyTCPServer(SocketServer.ThreadingTCPServer): 
    allow_reuse_address = True 

httpd = MyTCPServer(('localhost', 8080), CustomHandler) 
httpd.allow_reuse_address = True 
print "serving at port", 8080 
httpd.serve_forever() 

試試看:

HTTP GET /folder/?id=500x - >"FOLDER ID: 500x"

編輯:

好了,如果你還沒有使用前SimpleHTTPServer-的東西,你基本上實現基本請求處理程序,實現do_GET(),do_PUT(),do_POST()等

我最常做的就是解析請求字符串(重新使用),模式匹配,看看我能找到一個請求處理程序,如果沒有,處理請求爲靜態內容如果可能的請求。

你說要提供靜態內容,如果可能的話,那麼你應該翻轉這種模式匹配周圍,並先看看請求的文件的存儲相匹配,並且如果沒有,那麼對陣處理器:)

+0

首先,謝謝!它表明可以防止重定向。但是,它好像這個處理程序不像我習慣的那樣提供靜態文件。我基本上想要的是能夠提供任何可用的靜態文件路徑,完全忽略查詢字符串部分。 – Marian

+0

只需在do_GET()方法中添加邏輯,我已經做了一個更新,只是你認爲使用web.py的 –

+0

?它非常輕巧,只是上面代碼的一小部分。 –

3

要做到這一點,以確保查詢參數保持他們應該正確的做法,是確保你做文件名的請求,而不是直接讓SimpleHTTPServer的重定向到您的index.html

對於例如http://localhost:8000/?param1=1確實重定向(301),並改變鏈接直接http://localhost:8000/?param=1/與所述查詢參數弄亂。

但是http://localhost:8000/index.html?param1=1(使索引文件明確)加載正確。

所以只是不讓SimpleHTTPServer做一個url重定向解決了這個問題。