向BaseHTTPRequestHandler发送值

0 投票
1 回答
1121 浏览
提问于 2025-04-17 07:50

我正在用Python创建一个简单的网页服务器,使用的是HTTPServer和BaseHTTPRequestHandler。到目前为止,我的代码是这样的:

from handler import Handler #my BaseHTTPRequestHandler

def run(self):
    httpd = HTTPServer(('', 7214), Handler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

我想设置一个基础路径,让这个处理器可以从中提供文件,但我不太确定该怎么做,因为它还没有被实例化。我觉得这应该很简单明了,但我就是想不出来怎么做。我知道我可以在处理器类里面设置,但如果可以的话,我想在这里设置,因为我所有的配置都是在这里读取的。

1 个回答

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()

撰写回答