Python urllib2 HTTPBasicAuthHandler [英] Python urllib2 HTTPBasicAuthHandler
问题描述
代码如下:
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
它工作得很好.唯一的问题是,当使用了错误的用户名或密码时,需要永远打开到 url @
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')
它不会抛出任何错误,只是永远执行 urlopen 语句.
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.
推荐答案
它应该抛出一个错误,更准确地说是一个 urllib2.HTTPError,代码字段设置为 401,您可以在下面看到一些改编的代码.我留下了你的通用 try/except 结构,但实际上,不要使用通用的 except 语句,只捕捉你期望可能发生的事情!
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
这篇关于Python urllib2 HTTPBasicAuthHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!