开发者

How do I serve and log my current directory with a python web server?

开发者 https://www.devze.com 2023-01-14 14:17 出处:网络
I need to create a webserver that will respond to GET requests by serving pages from a specified folder, as well as log the pages the user is GETting, and the IP of the user.

I need to create a webserver that will respond to GET requests by serving pages from a specified folder, as well as log the pages the user is GETting, and the IP of the user.

The main trouble comes from me not knowing how to serve the directory listing to the user when overriding the do_GET method. Here is my code so far:

#!/u开发者_运维问答sr/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()


You need to use dir_listing() to list directories. Rather than writing it here, I would suggest you look at the python cookbook/ recipes for detailed directions and understanding.

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

精彩评论

暂无评论...
验证码 换一张
取 消