Python urllib2 HTTPBasicAuthHandler

ε祈祈猫儿з 提交于 2019-11-30 07:41:06

问题


Here is the code:

import urllib2 as URL

def get_unread_msgs(user, passwd):
    auth = URL.HTTPBasicAuthHandler()
    auth.add_password(
            realm='New mail feed',
            uri='https://mail.google.com',
            user='%s'%user,
            passwd=passwd
            )
    opener = URL.build_opener(auth)
    URL.install_opener(opener)
    try:
        feed= URL.urlopen('https://mail.google.com/mail/feed/atom')
        return feed.read()
    except:
        return None

It works just fine. The only problem is that when a wrong username or password is used, it takes forever to open to url @

feed= URL.urlopen('https://mail.google.com/mail/feed/atom')

It doesn't throw up any errors, just keep executing the urlopen statement forever.

How can i know if username/password is incorrect.

I thought of a timeout for the function but then that would turn all error and even slow internet into a authentication error.


回答1:


It should throw an error, more precisely an urllib2.HTTPError, with the code field set to 401, you can see some adapted code below. I left your general try/except structure, but really, do not use general except statements, catch only what you expect that could happen!

def get_unread_msgs(user, passwd):
    auth = URL.HTTPBasicAuthHandler()
    auth.add_password(
            realm='New mail feed',
            uri='https://mail.google.com',
            user='%s'%user,
            passwd=passwd
            )
    opener = URL.build_opener(auth)
    URL.install_opener(opener)
    try:
        feed= URL.urlopen('https://mail.google.com/mail/feed/atom')
        return feed.read()
    except HTTPError, e:
        if e.code == 401:
            print "authorization failed"            
        else:
            raise e # or do something else
    except: #A general except clause is discouraged, I let it in because you had it already
        return None

I just tested it here, works perfectly



来源:https://stackoverflow.com/questions/3078638/python-urllib2-httpbasicauthhandler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!