Created
September 9, 2019 03:07
-
-
Save wongjustin99/111cbe29f9be40e1b6396262ea22973c to your computer and use it in GitHub Desktop.
python_http_server_with_plaintext_contenttype
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 | |
# Mostly sourced from https://stackoverflow.com/questions/37585147/unable-to-view-files-in-a-browser-with-python-http-server | |
from http.server import SimpleHTTPRequestHandler, test | |
import argparse | |
class InlineHandler(SimpleHTTPRequestHandler): | |
def end_headers(self): | |
mimetype = self.guess_type(self.path) | |
is_file = not self.path.endswith('/') | |
# This part adds extra headers for some file types. | |
if is_file and mimetype in ['text/plain', 'application/octet-stream']: | |
self.send_header('Content-Type', 'text/plain') | |
self.send_header('Content-Disposition', 'inline') | |
super().end_headers() | |
# The following is based on the standard library implementation | |
# https://github.com/python/cpython/blob/3.6/Lib/http/server.py#L1195 | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--bind', '-b', default='', 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