Skip to content

Instantly share code, notes, and snippets.

@vigo vigo/json_server.py
Last active Apr 4, 2018

Embed
What would you like to do?
Basic JSON webserver
#!/usr/bin/env python
import sys
import time
import argparse
import os
import json
import socketserver
from http.server import BaseHTTPRequestHandler
class BasicWebserver(BaseHTTPRequestHandler):
"""
Basic json server. Goto you /path/to/folder/ put a valid json file in it
and serve!
Requirements:
- Python 3.6.3+
Installation;
$ cd ~/bin/
$ curl -o json_server "RAW Version of this gist"
$ chmod +x json_server
Now you can call `json_server`
"""
def _set_response(self, code=200, content_type='text/html'):
self.send_response(code)
self.send_header('Content-type', content_type)
self.end_headers()
def json_response(self, incoming, encoding='utf-8'):
self.wfile.write(bytes(json.dumps(incoming), encoding=encoding))
def do_GET(self):
response_code = 200
response_content_type = 'application/json'
base_dir = os.getcwd()
if any(self.path.split('/')):
json_file = os.path.join(base_dir, *self.path.split('/')[1:])
try:
with open(json_file, 'r') as fp:
response_data = json.loads(fp.read())
except FileNotFoundError:
response_code = 404
response_data = dict(status=response_code, message='YOU fucked up!')
else:
response_code = 500
response_data = dict(status=response_code, message='I fucked up!')
self._set_response(code=response_code, content_type=response_content_type)
self.json_response(response_data)
def main():
parser = argparse.ArgumentParser(description='JSON web server')
parser.add_argument(
'-V',
'--version',
action='version',
version='%(prog)s 0.1.0',
)
parser.add_argument(
'--host',
type=str,
default='0.0.0.0',
help='Server host',
)
parser.add_argument(
'-p',
'--port',
type=int,
default=8000,
help='Server port number',
)
args = parser.parse_args()
try:
server_address = (args.host, args.port)
httpd = socketserver.TCPServer(server_address, BasicWebserver)
print('serving on {host} at {port}'.format(
host=args.host,
port=args.port,
))
httpd.serve_forever()
except KeyboardInterrupt:
print(' Quiting...')
httpd.server_close()
time.sleep(3) # Wait 3 seconds to free port...
return 0
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.