如何使用urlfetch检测无效的URL

时间:2016-03-08 14:14:40

标签: python google-app-engine google-app-engine-python

我使用以下方法获取gravatar

def fetch_gravatar(email):
    incorrect_base_url = 'http://ww.grvatar.com/avatar/'
    correct_base_url = 'http://www.gravatar.com/avatar/'
    gravatar_url = correct_base_url + hashlib.md5(email).hexdigest() + '?'
    gravatar_url2 = incorrect_base_url + hashlib.md5(email).hexdigest() + '?'
    size = str(feconf.GRAVATAR_SIZE_PX)
    gravatar_url += urllib.urlencode({'d':'identicon', 's':size})
    result = urlfetch.fetch(gravatar_url, headers={'Content-Type': 'image/png'})
    if result.status_code == 200:
        encoded_body = base64.b64encode(result.content)
        print result.status_code
        return 'data:{};base64,{}'.format('image/png', encoded_body)
    else:
        print result.status_code
        return '/images/avatar/user_blue_72px.png'

无论我使用urlfetch还是gravatar_url拨打gravatar_url2,它总是将result.status_code打印为200.如何查看我的网址是否合适?

1 个答案:

答案 0 :(得分:1)

此网址http://ww.grvatar.com/avatar/返回HTTP 302(重定向)。很可能您需要在调用urlfetch 1

时设置follow_redirect = False