tags:

views:

60

answers:

1

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.

A: 

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

KillianDS
Yes, it works. But it stop when I the password is incorrect.It does not throw any Exceptions. Just keeps processing feed= URL.urlopen('https://mail.google.com/mail/feed/atom')
Owais Lone
You could check your network settings (maybe you're behind a freaky proxy that goes crazy on 401's?). I tested it here, with the google feed, correct username and wrong password and the snippet works fine, it fails but does not go in infinite processing.
KillianDS