Reputation: 2730
I am creating a simple web server using HTTPServer and BaseHTTPRequestHandler in Python. Here is what I have so far:
from handler import Handler #my BaseHTTPRequestHandler
def run(self):
httpd = HTTPServer(('', 7214), Handler)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
I want to set the base path for the Handler to serve files from, but I am not sure how to do that since it hasn't been instantiated yet? I have a feeling that this is really easy/obvious, but I cannot think how to do it. I know I can do it inside of the Handler class, but I want to do it from here if possible, since all of my configurations are read here.
Upvotes: 0
Views: 1158
Reputation: 3506
Since no one wanted to answer your question...
Just replace the part in the code with the comment "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()
Upvotes: 1