I recommend not using execfile
. Instead, you can dynamically import the python file they request as a module using the builtin __import__
function. Here's a complete, working example that I just wrote and tested:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
filename = self.path.lstrip("/")
self.wfile.write("You requested " + filename + "\n\n")
if filename.endswith(".py"):
pyname = filename.replace("/", ".")[:-3]
module = __import__(pyname)
self.wfile.write( module.do_work() )
HTTPServer(("",8080), Handler).serve_forever()
So in this case, if someone visits http://localhost:8080/some_page then "You requested some_page" will be printed.
But if you request http://localhost:8080/some_module.py then the file some_module.py
will be imported as a Python module and the do_work
function in that module will be called. So if that module contains the code
def do_work():
return "Hello World!"
and you make that request, then the resulting page will be
You requested some_module.py
Hello World!
This should be a good starting point for dealing with such things. As an aside, if you find yourself wanting a more advanced web server, I highly recommend CherryPy.