Created
June 25, 2021 00:39
-
-
Save alejandrobernardis/8b655ff1f2cb01e829643916bcb8ffaa to your computer and use it in GitHub Desktop.
Simple Server
This file contains hidden or 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
{ | |
"error": "e200", | |
"message": [ | |
{"code": 1, "message": "message number one"}, | |
{"code": 2, "message": "message number two"}, | |
{"code": 3, "message": "message number ..."}, | |
{"code": 4, "message": "message number ..."}, | |
{"code": 5, "message": "message number ..."} | |
] | |
} |
This file contains hidden or 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
run: | |
python simple_server.py |
This file contains hidden or 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
import json | |
import socketserver | |
from http.server import SimpleHTTPRequestHandler | |
from pathlib import Path | |
cnx = ('0.0.0.0', 8000) | |
response = { | |
'error': 'e100', | |
'message': [ | |
{'code': 1, 'message': 'message number one'}, | |
{'code': 2, 'message': 'message number two'}, | |
] | |
} | |
root = Path(__file__).parent | |
external_data = root.joinpath('data.json') | |
class SimpleRequest(SimpleHTTPRequestHandler): | |
def do_GET(self): | |
try: | |
status = 200 | |
if external_data.is_file(): | |
with external_data.open('rb') as f: | |
output = f.read() | |
else: | |
output = response | |
except Exception as e: | |
status = 400 | |
output = {'error': str(e)} | |
if isinstance(output, dict): | |
output = json.dumps(output).encode() | |
self.send_response(status) | |
self.send_header('Content-type', 'application/javascript') | |
self.end_headers() | |
self.wfile.write(output) | |
return | |
def main(): | |
print(f'Simple Server starting in {":".join([str(i) for i in cnx])}.') | |
x = socketserver.TCPServer(cnx, SimpleRequest) | |
x.allow_reuse_address = True | |
try: | |
x.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
except Exception as e: | |
print(e) | |
finally: | |
print('Bye!') | |
x.server_close() | |
x.shutdown() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment