Last active
June 7, 2024 11:57
-
-
Save riga/74b5df4c425817f0563ea16ece2c78d7 to your computer and use it in GitHub Desktop.
static server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
# python imports | |
import os | |
import cherrypy | |
class Server(object): | |
def __init__(self, root, host="127.0.0.1", port=8080, auth=None): | |
self.root = root | |
self.host = host | |
self.port = port | |
def basic_auth(realm, username, password): | |
return auth is not None and (username, password) == tuple(auth) | |
self.config = { | |
"global": { | |
"server.socket_host": host, | |
"server.socket_port": port, | |
"server.thread_pool": 10, | |
}, | |
"/": { | |
"tools.staticdir.on": True, | |
"tools.staticdir.dir": root, | |
"tools.auth_basic.on": auth is not None, | |
"tools.auth_basic.realm": "protected", | |
"tools.auth_basic.checkpassword": basic_auth, | |
}, | |
} | |
@cherrypy.expose | |
def index(self): | |
return open(os.path.join(self.root, "index.html")) | |
if __name__ == "__main__": | |
from argparse import ArgumentParser | |
parser = ArgumentParser(description="start a static cherrypy server") | |
parser.add_argument( | |
"root", | |
metavar="PATH", | |
nargs="?", | |
default=os.getcwd(), | |
help="the server root path, default: .", | |
) | |
parser.add_argument( | |
"--host", | |
"-H", | |
default="0.0.0.0", | |
help="the server host, default: 0.0.0.0", | |
) | |
parser.add_argument( | |
"--port", | |
"-P", | |
type=int, | |
default=8080, | |
help="the server port, default: 8080", | |
) | |
parser.add_argument( | |
"--auth", | |
"-a", | |
metavar=("USER", "PASSWORD"), | |
nargs=2, | |
help="user and password for basic authentication", | |
) | |
parser.add_argument( | |
"--authFile", | |
"-f", | |
dest="authfile", | |
metavar="FILE", | |
help="a file that contains user and password for basic authentication in two lines", | |
) | |
args = parser.parse_args() | |
args.root = os.path.expandvars(os.path.expanduser(args.root)) | |
args.root = os.path.abspath(args.root) | |
# check auth | |
if not args.auth and args.authfile: | |
with open(args.authfile, "r") as f: | |
user = f.readline().strip() | |
password = f.readline().strip() | |
args.auth = (user, password) | |
# start | |
server = Server(args.root, host=args.host, port=args.port, auth=args.auth) | |
cherrypy.quickstart(server, "/", config=server.config) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment