Last active
September 17, 2023 12:58
-
-
Save chudilka1/1aac5a19a98a7942c49219b463211d34 to your computer and use it in GitHub Desktop.
Python mock server
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 | |
""" | |
Very simple HTTP server in Python | |
1. Create `mock-server` dir | |
2. Put this script and .json files (representing responses) into the folder | |
3. In CLI run: cd ~/mock-server && python3 server.py [<any_available_and_preferrable_port>] - server will be running on localhost (127.0.0.1:<port>) | |
4. To request resources locally: `localhost:<port>/<name_of_resource>.json` | |
5. To request resources remotely: | |
5.1 Find your IP: `ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'` | |
5.2 Request resource: http://<you.IP>:<host>/<name_of_resource>.json` | |
!!! If a client closes before the response completely recieved or for any other reasons (restrictions), the server may error with `BrokenPipeError: [Errno 32] Broken pipe` | |
""" | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import logging | |
import json | |
import time | |
class S(BaseHTTPRequestHandler): | |
def sleep(self, seconds): | |
logging.warning("Sleeping for %s seconds.", seconds) | |
time.sleep(seconds) | |
def _set_response(self): | |
self.send_response(200) # <---- scpecify status to return | |
self.send_header('Content-type', 'application/json') # <---- scpecify headers to return | |
self.send_header('Test-header', 'test_header_1') | |
self.end_headers() | |
stripped_path_to_file = str(self.path)[1:] # <---- removes a slash from the path | |
logging.info("Requested PATH (file): '%s'", stripped_path_to_file) | |
# secondsToSleep = 5 | |
# self.sleep(secondsToSleep) # <----- use this to test timeouts | |
with open(stripped_path_to_file, "r") as data_file: | |
data = json.load(data_file) | |
payload = json.dumps(data) | |
logging.info("Content of '%s': %s", stripped_path_to_file, payload) | |
self.wfile.write(payload.encode('utf-8')) | |
def do_GET(self): | |
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers)) | |
self._set_response() | |
def do_POST(self): | |
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data | |
post_data = self.rfile.read(content_length) # <--- Gets the data itself | |
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", | |
str(self.path), str(self.headers), post_data.decode('utf-8')) | |
self._set_response() | |
def run(server_class=HTTPServer, handler_class=S, port=8080): | |
logging.basicConfig(level=logging.INFO) | |
server_address = ('', port) | |
httpd = server_class(server_address, handler_class) | |
logging.info('Starting Python Server\n') | |
try: | |
httpd.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
httpd.server_close() | |
logging.info('Stopping Python Server\n') | |
if __name__ == '__main__': | |
from sys import argv | |
if len(argv) == 2: | |
run(port=int(argv[1])) | |
else: | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment