import os
import web
import traceback
import datetime
from functools import wraps

### Url mappings

urls = [
    '/', 'index',

]
def addfolderhandler(f,root):
        u = os.path.join(root,f)
        u=u.strip("/").strip("\\")
        ident=u.lstrip("C:/Users/James/Desktop/it").replace("/","SLASH").replace("\\","SLASH").replace(".","DOT").strip() #replace invalid python expressions with valid ones
        globals()[ident] = "<h1>Directory listing for:%s</h1><hr>"%u+''.join(["<a href="+i+">"+i.lstrip(root)+"</a><br/>" for i in os.listdir(u)])+"<i>Python Server</i>"
        if ident=="":
            return

        try:
            exec("""
class %(classname)s:
    def GET(self):
        global %(data)s
        return %(data)s
            """%{"classname":ident+"server","data":ident}, globals(), globals())  #create a class as if were created in the global scope by passing in globals() as locals
            urls.extend((u.lstrip("C:/Users/James/Desktop/it").replace("\\","/"),ident+"server")) #use u not ident because ident has stuff like SLASH and DOT
        except:
            print"WARNING:Cannot Make Folder Handler for:"+ident
def addfilehandler(f,root):
        u = os.path.join(root,f)
        u=u.strip("/").strip("\\")
        ident=u.lstrip("C:/Users/James/Desktop/it").replace("/","slash").replace("\\","SLASH").replace(".","DOT") #replace invalid python expressions with valid ones
        globals()[ident] = open(u,mode='rb').read()
        exec("""
class %(classname)s:
    def GET(self):
        global %(data)s
        return %(data)s
        """%{"classname":ident+"server","data":ident}, globals(), globals())  #create a class as if were created in the global scope by passing in globals() as locals
        urls.extend((u.lstrip("C:/Users/James/Desktop/it").replace("\\","/"),ident+"server")) #use u not ident because ident has stuff like SLASH and DOT
def init():
    global urls
    for root, dirs, files in os.walk("C:/Users/James/Desktop/it"):
        if "web" in dirs:
            dirs.remove("web")
        for f in dirs:
            addfolderhandler(f,root)
        for f in files:
            if "server.py" in f:
                continue
            elif "maintence.py" in f:
                continue
            elif "log.txt" in f:
                continue
            addfilehandler(f,root)
    urls = tuple(urls)
init()
class index:
    def GET(self):
        return "<!DOCTYPE html><html><link rel=\"icon\" href=\"favicon.ico\" type=\"image/x-icon\"/>hi</html>"
class favicon:
    def GET(self):
        return open('favicon.ico',mode='rb').read()
def notfound():
    return web.notfound("<!DOCTYPE html><html><link rel=\"icon\" href=\"favicon.ico\" type=\"image/x-icon\"/><b><h1>404 Not Found</h1></b><hr/>Python Server</html>")
app = web.application(urls, globals())
app.notfound = notfound
if __name__ == '__main__':
    app.run()

While executing, the nothingness variable encounters a error with exec.
When I printed the variable, I got a newline.
I got nothing for the variable type.

Dani AI

Generated

Most likely causes: the dynamically generated identifier fed to exec is invalid or empty, and the bare except: is hiding the real error. str.lstrip("C:/Users/...") does not remove that prefix — it strips any leading characters found in the argument string — so the relative path or identifier can become malformed (empty, start with a digit, contain newlines or other invalid characters). That explains why printing the value looked like "just a newline" and why exec fails with a syntax error that never shows up because the code swallows exceptions.

Quick diagnostics to make the real problem visible:

  • Replace the bare except: with an explicit exception handler or remove it so the traceback appears (or use traceback.print_exc()).
  • Print the debug form of strings with repr(...) to reveal hidden characters and exact contents of the identifier and the class-source string.
  • Use os.path.relpath() or os.path.basename() instead of lstrip() to get a predictable relative path.

A safer pattern (sanitise names and avoid exec) — sanitize the path into a valid Python identifier, and create handler classes programmatically with type() so exec is not required:

import os, re

def sanitize_ident(path, base="C:/Users/James/Desktop/it"):
    rel = os.path.relpath(path, base).replace(os.sep, '_')
    name = re.sub(r'[^0-9A-Za-z_]', '_', rel)
    if name and name[0].isdigit():
        name = '_' + name
    return name or 'root'

def make_handler(data, classname):
    def GET(self):
        return data
    return type(classname, (), {'GET': GET})

# example usage
ident = sanitize_ident(u)
classname = ident + '_server'
globals()[classname] = make_handler(some_data, classname)
urls.extend((os.path.relpath(u, "C:/Users/James/Desktop/it").replace('\\','/'), classname))

Extra notes: avoid creating empty-string keys in globals() (they behave oddly), ensure bytes/text are the expected type for the web framework (Python 2 vs 3 differences), and prefer small, readable helper functions — as hinted, clearer code makes these bugs much easier to find.

Good grief that code is hard to read!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.