Python - loading Module in a Python Webserver

im trying to get Python to load a module depening on what page is requested from a browser, I have it working if the .py file is in the root of the script, but cant seem to get it working if its in a subdirectory.

html files work everywhere, Id appreciate it if someone could help me get the python files to work aswell from any directory.

im running Python 2.7 on win 7 64bit SP1

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import mimetypes

#import pri
port = 888
host = "0.0.0.0"

class MyHandler(BaseHTTPRequestHandler):

def do_GET(self):
    try:
        #RequestedURL = self.path
        mimeType = mimetypes.guess_type(self.path)[0]
        fileType = mimetypes.guess_extension(mimeType)
        infoList = [mimeType, fileType]

        if infoList[1] != ".py":
            self.send_response(200)
            self.send_header('Content-type', mimeType)
            self.end_headers()
            f = open(curdir + sep + self.path, "rb")
            self.wfile.write(f.read())
            f.close()
            return

        if fileType == ".py":
            pythonFilename = self.path.lstrip("/")
            self.send_response(200)
            self.send_header('Content-type',    'text/html')
            self.end_headers()
            pyname = pythonFilename.replace("/", ".")[:-3]
            print pythonFilename
            print pyname
            temp1 = pyname.split(".")
            temp2 = temp1[-1]
            print temp2
            module = __import__(root.index)
            self.wfile.write(module.root.index.do_work())
            #module = __import__("test.index")
            #self.wfile.write( module.index.do_work())
            return

        return

    except IOError:
        self.send_error(404,'File Not Found: %s' % self.path)


def do_POST(self):
    global rootnode
    try:
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            query=cgi.parse_multipart(self.rfile, pdict)
        self.send_response(301)

        self.end_headers()
        upfilecontent = query.get('upfile')
        print "filecontent", upfilecontent[0]
        self.wfile.write("<HTML>POST OK.<BR><BR>");
        self.wfile.write(upfilecontent[0]);

    except :
        pass

def main():
try:
    server = HTTPServer((host, port), MyHandler)
    print 'started httpserver:'
    print  ("Host: "  + (host))
    print  ("Port: "  + str(port))

    server.serve_forever()
except KeyboardInterrupt:
    print '^C received, shutting down server'
    server.socket.close()

if __name__ == '__main__':
main()

Answers


The first thing to do is to make sure the sub-directory has a file named

__init__.py

in it. This file can be blank, but you won't be able to do imports without it. Then, you should know that if you're importing from a sub-directory, you'll have to include something like

module = __import__("subdirectory.jack2")

That is, you'll need to include the name of the sub-directory the module is stored in when importing the module.

If you want to import from a directory that is not a sub-directory of whatever directory you're working in, you'll have to make sure that it is included in the python path. You can modify the path by setting sys.path simply by importing the sys module, and appending a new path to wherever your modules are stored:

import sys
sys.path.append("full/path/to/directory/to/import/from")

Edit in response to the comments:

When using the builtin function __import__, it is important to realize that it returns the top-level module, not the one that you'd like to import. So, if you want to access the module you just imported, you'll need to do something like this:

module = __import__("mymodule")
result = module.mymodule.myfunction()

Need Your Help

What is the Difference between Decode and Decrypt?

encryption decode terminology

This decrypt and decode word is used by most of the people.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.