我不確定重定向是如何生成的......我試過實現一個非常基本的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()等
我最常做的就是解析請求字符串(重新使用),模式匹配,看看我能找到一個請求處理程序,如果沒有,處理請求爲靜態內容如果可能的請求。
你說要提供靜態內容,如果可能的話,那麼你應該翻轉這種模式匹配周圍,並先看看請求的文件的存儲相匹配,並且如果沒有,那麼對陣處理器:)
SimpleHTTPServer僅提供文件。使用其他的東西來處理請求中的參數。 –