我正在使用Python语言中的HTTPServer和BaseHTTPRequestHandler创建一个简单的web服务器。这是我到目前为止所知道的:
from handler import Handler #my BaseHTTPRequestHandler
def run(self):
httpd = HTTPServer(('', 7214), Handler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()我想为Handler设置提供文件的基本路径,但我不确定如何做,因为它还没有被实例化?我有一种感觉,这真的很容易/显而易见,但我想不出该怎么做。我知道我可以在Handler类中完成,但如果可能的话,我想从这里完成,因为我的所有配置都在这里读取。
发布于 2011-12-09 03:08:43
既然没人愿意回答你的问题..。
只需将代码中的部分替换为注释"yourpath“即可。
import os
import posixpath
import socket
import urllib
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class MyFileHandler(SimpleHTTPRequestHandler):
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = '/' # yourpath
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 run():
try:
httpd = HTTPServer(('', 7214), MyFileHandler)
httpd.serve_forever()
except KeyboardInterrupt:
pass
except socket.error as e:
print e
else:
httpd.server_close()https://stackoverflow.com/questions/8405764
复制相似问题