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.
- http://code.activestate.com/recipes/392879-my-first-application-server/
精彩评论