I do not think that re-education of an exception is an appropriate way to solve this problem.
As Jonathan Vanasco said,
if you open a.com, and 301 redirects to b.com, urlopen will automatically follow this because an HTTPError with a redirect has been raised. if b.com raises a URLError, the code above marks a.com as non-existent
My solution is to overwrite redirect_request from urllib2.HTTPRedirectHandler
import urllib2 class NewHTTPRedirectHandler(urllib2.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): m = req.get_method() if (code in (301, 302, 303, 307) and m in ("GET", "HEAD") or code in (301, 302, 303) and m == "POST"): newurl = newurl.replace(' ', '%20') newheaders = dict((k,v) for k,v in req.headers.items() if k.lower() not in ("content-length", "content-type") )
try redirecting the url to an unknown url:
import os from flask import Flask,redirect app = Flask(__name__) @app.route('/') def hello(): # return 'hello world' return redirect("http://a.com", code=302) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
And the result:
error http:
superhan
source share