Getting ready

There are plenty of third-party web services on the internet that can be freely accessed for prototyping purposes. However, we do not want to rely on an external service because its API may change or it might even go offline.

For this recipe, we will implement our custom HTTP server, which generates a random JSON response that will be printed on our separate GUI application:

import time
import json
import random
from http.server import HTTPServer, BaseHTTPRequestHandler

class RandomRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Simulate latency
time.sleep(3)

# Write response headers
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()

# Write response body
body = json.dumps({'random': random.random()})
self.wfile.write(bytes(body, "utf8"))

def main():
"""Starts the HTTP server on port 8080"""
server_address = ('', 8080)
httpd = HTTPServer(server_address, RandomRequestHandler)
httpd.serve_forever()

if __name__ == "__main__":
main()

To start this server, run the server.py script and leave the process running to accept incoming HTTP requests on local port 8080.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset