Reputation: 4488
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()
Upvotes: 0
Views: 165
Reputation: 11
In this case the code is not checking for unsuccessful requests, the try will catch some exceptions but not all. What you want is the following function raise_for_status()
that will raise an exception in case of a failed status code. See also Response raise for status
Upvotes: 1