简体   繁体   中英

Handling unsuccessful requests in python

I would like to make various http requests and display the actual response status code and reason regardless of any http exceptions, for eg 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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM