将值发送到BaseHTTPRequestHandler

时间:2011-12-06 19:41:33

标签: python

我正在使用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类中完成它,但是如果可能的话我想从这里开始,因为我的所有配置都在这里阅读。

1 个答案:

答案 0 :(得分:1)

因为没有人想回答你的问题......

只需使用注释“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()