Created
September 23, 2022 06:38
python简单文件服务器,主要是支持指定content-type,
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 python3 | |
from http.server import SimpleHTTPRequestHandler, test | |
import argparse | |
import os | |
import posixpath | |
import sys | |
class InlineHandler(SimpleHTTPRequestHandler): | |
extensions_map = { | |
'.txt': 'text/plain ;charset=UTF-8', | |
'.md': 'text/plain ;charset=UTF-8', | |
'.patch': 'text/plain ;charset=UTF-8', | |
'.apk': 'application/vnd.android.package-archive', | |
} | |
def guess_type(self, path): | |
base, ext = posixpath.splitext(path) | |
if ext in self.extensions_map: | |
return self.extensions_map[ext] | |
return super().guess_type(path) | |
def end_headers(self): | |
self.send_my_headers() | |
super().end_headers() | |
def send_my_headers(self): | |
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate") | |
self.send_header("Pragma", "no-cache") | |
self.send_header("Expires", "0") | |
# 报错只打印一行信息就行了, | |
def handle(self) -> None: | |
try: | |
return super().handle() | |
except Exception as e: | |
print("Exception: " + str(e)) | |
if __name__ == '__main__': | |
abspath = os.path.abspath(sys.argv[0]) | |
dname = os.path.dirname(abspath) | |
os.chdir(dname) | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--bind', '-b', default='0.0.0.0', metavar='ADDRESS', | |
help='Specify alternate bind address ' | |
'[default: all interfaces]') | |
parser.add_argument('port', action='store', | |
default=8000, type=int, | |
nargs='?', | |
help='Specify alternate port [default: 8000]') | |
args = parser.parse_args() | |
test(InlineHandler, port=args.port, bind=args.bind) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment