如何用Python网络服务器服务并记录当前目录?

1 投票
1 回答
1332 浏览
提问于 2025-04-16 03:33

我需要创建一个网页服务器,当用户发送GET请求时,它能从指定的文件夹中提供网页,同时记录用户访问的网页和用户的IP地址。

我遇到的主要问题是,我不知道在重写do_GET方法时,如何将文件夹的目录列表展示给用户。以下是我目前的代码:

#!/usr/bin/env python
import logging
import SimpleHTTPServer
import SocketServer
import SimpleHTTPServer
import BaseHTTPServer
import os

PORT = 8001
LOG_FILENAME = 'log.txt'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        try:
            #self.send_response(200)
            #self.send_header('Content-type', 'text/html')
            #self.end_headers();
            #self.list_directory(self.path)
            #os.listdir()
            logging.debug('Test text')            
        except IOError:
            print "nothing"

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), MyHandler)

print "serving at port", PORT
httpd.serve_forever()

1 个回答

1

你需要使用 dir_listing() 这个函数来列出目录。与其在这里详细写,不如建议你去看看 Python 的食谱,里面有更详细的说明和理解。

  1. http://code.activestate.com/recipes/392879-my-first-application-server/

撰写回答