Skip to content

Instantly share code, notes, and snippets.

@jdkanani
Last active September 21, 2024 14:44
Show Gist options
  • Save jdkanani/4503653 to your computer and use it in GitHub Desktop.
Save jdkanani/4503653 to your computer and use it in GitHub Desktop.
Python SimpleHTTPServer : Routing sample
#!/usr/bin/env python
import os
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
ROUTES = [
('/', '/var/www/doc-html')
]
class MyHandler(SimpleHTTPRequestHandler):
def translate_path(self, path):
# default root -> cwd
root = os.getcwd()
# look up routes and get root directory
for patt, rootDir in ROUTES:
if path.startswith(patt):
path = path[len(patt):]
root = rootDir
break
# new path
return os.path.join(root, path)
if __name__ == '__main__':
httpd = HTTPServer(('127.0.0.1', 8000), MyHandler)
httpd.serve_forever()
@AmirEstiri
Copy link

AmirEstiri commented Jul 31, 2020

for python3 change from BaseHTTPServer import HTTPServer and
from SimpleHTTPServer import SimpleHTTPRequestHandler to from http.server import HTTPServer and
from http.server import SimpleHTTPRequestHandler

@vaibhavkumar049
Copy link

how to set different routes like localhost:8000/home for example

@bhardwajRahul
Copy link

any example for localhost:8000/home

@id-jordan-stefanelli
Copy link

    def translate_path(self, path):
        some_route = 'home'
        if some_route in path:
            self.my_other_handler()
        ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment