tags:

views:

431

answers:

2

I have a user and a password and I'd like to use Twitter API (I'm using python-twitter) to check if those are valid data.

+1  A: 

urllib2 will raise HTTPError if the credentials are wrong, and the message will be 'HTTP Error 401: Unauthorized'. You could use a temporary instance of the API to make an authorized request (GetFriends(), for example) in a try/except block to determine if the credentials are valid.

import twitter, urllib2
checkCreds = twitter.Api(username, pass)
try:
  checkCreds.GetFriends()
except urllib2.HTTPError, status:
  if status.find('401') != -1:
    print 'Invalid username/password'

Twitter will intentionally allow requests with missing or incorrect credentials for publicly-accessible areas such as GetPublicTimeline() or GetUserTimeline().

echoback
A: 

If you grab the 0.7 version of python-twitter, a VerifyCredentials method has been added. If the returned value is None then the username/password combo was incorrect.

I liked using api.GetUser(username) first to check if they provided a valid username and then using api.VerifyCredentials() to check the password -- this way I could informed the user which part of their login was incorrect.

As others have mentioned, Twitter is pushing for OAuth logins only and are expected to deprecate the existing username/passwd login method.

swanson
Where is 0.7? I can only find 0.6 at http://code.google.com/p/python-twitter/
Juanjo Conti
from svn, right
Juanjo Conti