views:

308

answers:

4

I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that?

import urllib2
import sys
import re
import base64
from urlparse import urlparse
import simplejson

def is_follows(follower, following):

    theurl = 'http://twitter.com/friendships/exists.json?user_a='+follower+'&user_b='+following

    username = 'uname1'
    password = 'pwd1'

    handle = urllib2.Request(theurl)

    base64string = base64.encodestring('%s:%s' % (username, password))
    authheader =  "Basic %s" % base64string
    handle.add_header("Authorization", authheader)
    fol=True
    try:
        fol = simplejson.load(urllib2.urlopen(handle))
    except IOError, e:
        # here we shouldn't fail if the username/password is right
        print "It looks like the username or password is wrong."
    return fol

Update: Indentation fixed.

+2  A: 

Three things:

  • Fix the indentation (but then I guess this was not done on purpose).
  • Use formatting instead of concatenation in constructing theurl.
  • Remove the fol variable. Rather, do the following:


try:
    return simplejson.load(urllib2.urlopen(handle))
except IOError, e:
    # here we shouldn't fail if the username/password is right
    print "It looks like the username or password is wrong."
    return False
Konrad Rudolph
A: 

Google threw this library with an Twitter API for Python at me. I think such an library would simplify this task alot. It has a GetFollowers() method that lets you look up if someone is following you.

Edit: It looks like you can't look up followers of arbitrary users.

unbeknown
Iterating thro a list of all followers is not an option as I know the username of the person that i want to verify.There is a friendship/exists.json twitter API for which python wrapper is not implemented.
Lakshman Prasad
+2  A: 

Konrad gave you a good answer with changes you can make to make your code more Pythonic. All I want to add is if you are interested in seeing some advanced code to do this same thing check out The Minimalist Twitter API for Python.

It can show you a Pythonic way to write an API that doesn't repeat itself (in other words follows DRY [don't repeat yourself] principles) by using dynamic class method construction using __getattr__() and __call__(). Your example would be something like:

fol = twitter.friendships.exists(user_a="X", user_b="Y")

even though the twitter class doesn't have "friendships" or "exists" methods/properties.

(Warning: I didn't test the code above so it might not be quite right, but should be pretty close)

Van Gale
+2  A: 

From your code it looks like you are trying to do a Basic HTTP Authentication. Is this right? Then you shouldn't create the HTTP headers by hand. Instead use the urllib2.HTTPBasicAuthHandler. An example from the docs:

import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')
unbeknown
This is precisely what I was looking for. Thanks!!
Lakshman Prasad
Konrad gave better tips for being pythonic. This answer is more a tip about using an api.
Sam Corder
I think both answers were good. Using the standard library as much as possible produces readable code that is potentially less buggy.
Van Gale