Skip to main content
 首页 » 编程设计

authentication之用于查找 x 是否在 Twitter 上关注 y 的 Python 代码。请使用更多 Pythonic 方式

2025年05月04日19Renyi-Fan

我用 Python 编写了一个 Twitter 应用程序。以下是我用于查找 x 是否在 y 之后的模块的代码。可以明显改进此代码。一种 pythonic 的方式来做到这一点?

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 

更新:缩进已修复。

请您参考如下方法:

从您的代码看来,您正在尝试进行基本 HTTP 身份验证。这是正确的吗?那么您不应该手动创建 HTTP header 。而是使用 urllib2.HTTPBasicAuthHandler。来自 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')