Skip to content

Instantly share code, notes, and snippets.

@gotev
Last active September 27, 2019 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotev/eb4c31e0b89461609e789a8472e7fb52 to your computer and use it in GitHub Desktop.
Save gotev/eb4c31e0b89461609e789a8472e7fb52 to your computer and use it in GitHub Desktop.
Static JSON File Server in Python 3
#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
base_path = os.path.dirname(__file__)
class StaticServer(BaseHTTPRequestHandler):
def execute_request(self):
filename = 'cached-responses' + self.path + '.json'
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
with open(os.path.join(base_path, filename), 'rb') as fh:
self.wfile.write(fh.read())
def do_POST(self):
self.execute_request()
def do_GET(self):
self.execute_request()
def run(server_class=HTTPServer, handler_class=StaticServer, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting Server on port {}'.format(port))
httpd.serve_forever()
run()
@gotev
Copy link
Author

gotev commented Sep 27, 2019

Static files are in cached-responses sub directory and all have .json extension

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