Chandrapal
Chandrapal

Reputation: 31

Whats the error in this Python(2.7) code?

I am writing a code to get the service code of any kind of URL

import requests
req = requests.get("http://www.google.com", allow_redirects = False)
code_from_url = req.status_code
print type(code_from_url)
codes = { 200:'Success', 301:'Moved Permanently', 400: 'Bad Request', 401:'Unauthorized', 403:'Forbidden', 404:'Not Found', 500:'Internal Server Error', 502:'Bad Gateway' }
print code_from_url
print codes[code_from_url]

But when I run this code I get an error on line 7 i.e. print codes[code_from_url] stating 'KeyError: 302'.

Upvotes: 0

Views: 231

Answers (1)

paxdiablo
paxdiablo

Reputation: 881383

Since your lookup collection (slightly reformatted):

codes = {
    200: 'Success',
    301: 'Moved Permanently',
    400: 'Bad Request',
    401: 'Unauthorized',
    403: 'Forbidden',
    404: 'Not Found',
    500: 'Internal Server Error',
    502: 'Bad Gateway'
}

actually has no key of 302, that's you are getting the KeyError exception.

Code 302 Found is meant to indicate to a client that a redirection is needed, while providing the ability for said client to update its own references to the resource. So there's (at least) three ways to handle this problem.


First option, if you don't actually care that you're being redirected (and you probably don't for http://www.google.com so this would be my preferred option), you can simply let the redirect happen without notification:

req = requests.get("http://www.google.com", allow_redirects = True)

Second, you can treat 302 as an error by adding it to your response collection:

codes = { 200:'Success', 301:'Moved Permanently', 302:'Found', ...

Thirdly, you can check for this 302 code and treat it as a special case, i.e., not as an error.

Upvotes: 1

Related Questions