I would like to make various http requests and display the actual response status code and reason regardless of any http exceptions, for e.g. if it returns 503 or 404 then just want to display that status code and handle it rather than throwing exception stack. However, what happens currently in the following is reason variable is never populated if the request is unsuccessful so the request summary result is never displayed.
Any suggestions?
import http.server import socketserver import socket import requests PORT = 5000 URL1 = "https://foo/" # URL2 = class Handler(http.server.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(("<br>Running on: %s" % socket.gethostname()).encode('utf-8')) if self.path == '/status': self.wfile.write(("<h1>status</h1>").encode('utf-8')) try: response = requests.get(URL1,verify=False) self.wfile.write(("<br>Request client connection : {}, Response Status: {}, Response Reason: {}".format(response.url, response.status_code, response.reason)).encode('utf-8')) except: self.wfile.write(("exception").encode('utf-8')) #self.wfile.write(("<br>Request client connection : {}, Response Status: {}, Response Reason: {}".format(response.url, response.status_code, response.reason)).encode('utf-8')) return return httpd = socketserver.TCPServer(("", PORT), Handler) print("serving at port: %s" % PORT) httpd.serve_forever()