您可以使用自定义脚本来初始化您的服务器并在其中定义您的路由,例如本文中建议的:
蟒蛇2:
server.py
import os
import posixpath
import urllib
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
# modify this to add additional routes
ROUTES = ( <- this is the "good stuff", make aliases for your paths
# [url_prefix , directory_path]
['/media', '/var/www/media'],
['', '/var/www/site'] # empty string for the 'default' match
)
class RequestHandler(SimpleHTTPRequestHandler):
def translate_path(self, path):
"""translate path given routes"""
# 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
if __name__ == '__main__':
BaseHTTPServer.test(RequestHandler, BaseHTTPServer.HTTPServer)
然后运行你的脚本:
python server.py
蟒蛇 3:
在 Python 3 中,BaseHTTPServer
和SimpleHTTPServer
模块已合并到http.server
模块中。所以你将不得不修改上面的脚本如下:
更改
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
至
import http.server
(如果您这样做,则应将调用修改为http.server.SimpleHTTPRequest
等)
或者
from http.server import BaseHTTPServer, SimpleHTTPServer, SimpleHTTPRequestHandler
(使用此选项调用保持与原始脚本相同)
然后运行服务器脚本:python server.py
在您的情况下:
您应该修改ROUTES
变量以满足您的需要。
例如,您想/html
从您的 url 中隐藏文件夹:
ROUTES = (
['', '/exact/path/to/folder/html'],
['/another_url_path', '/exact/path/to/another/folder'],
...
)
现在,如果您点击:http://localhost:8000/index.html
您将在您的主页中。
笔记:
默认情况下,此脚本将在执行到域 url时提供文件夹中包含的文件(例如,我server.py
在 Documents 文件夹中,然后当我运行它时,http://localhost:8000 url 将服务于我的 Documents 文件夹)。
您可以通过 Routes 更改此行为(请参阅代码上的“默认”匹配注释)或将脚本放在项目根文件夹中并从那里启动它。