我不确定重定向是如何生成的...我尝试实现一个非常基本的 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() 等。
然后我通常做的是解析请求字符串(使用 re),模式匹配,看看我是否可以找到请求处理程序,如果没有,如果可能,将请求作为静态内容请求处理。
您说如果可能的话您想提供静态内容,那么您应该翻转这个模式匹配,首先查看请求是否与文件存储匹配,如果不匹配,则与处理程序匹配:)