Using Tweepy API behind proxy

2019-09-15 05:33发布

问题:

I have a using Tweepy, a python wrapper for Twitter.I am writing a small GUI application in Python which updates my twitter account.

Currently, I am just testing if the I can get connected to Twitter, hence used test() call. I am behind Squid Proxy server.What changes should I make to snippet so that I should get my work done.

Setting http_proxy in bash shell did not help me.

def printTweet(self):
    #extract tweet string
    tweet_str = str(self.ui.tweet_txt.toPlainText()) ;
    #tweet string extracted.
    self.ui.tweet_txt.clear()  ;

    self.tweet_on_twitter(str);

def tweet_on_twitter(self,my_tweet) :
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET);
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) ;
    api = tweepy.API(auth) ;

    if api.test() :
        print 'Test successful' ;
    else :
        print 'Test unsuccessful';

回答1:

I guess you should set 'https_proxy' instead.

On my linux, I use this:

> export HTTPS_PROXY="http://xxxx:8888"

before running my Tweepy script.

Tweep uses 'requests' package for sending request, read http://docs.python-requests.org/en/master/user/advanced/#proxies for more.



回答2:

The proxy support in tweepy is severely lacking; there is a patch available that aims to fix that problem.

The patch switches Tweepy from using httplib directly to using urllib2 instead, which means it'd honour the http_proxy environment variable.



回答3:

EDIT: Turns out this isn't a viable answer, but I'm leaving it here for reference


Since a quick glance of the code shows that tweepy is using urllib2.urlopen & co., the easiest is possibly to just override the default opener...

# 'x.x.x.x' = IP of squid server
your_squid_server = urllib2.ProxyHandler({'http': 'x.x.x.x', 'https': 'x.x.x.x'})
new_opener = urllib2.build_opener(your_squid_server)
urllib2.install_opener(new_opener) 

Haven't get an environment to check that at the moment though...

Do the above before importing tweepy to make sure the new opener is in effect



回答4:

this is an old question, but hopefully this helps.

https://bitbucket.org/sakito/tweepy provides tweepy with urllib merged into it; the proxy settings works well. there is a little problem with the stream (in my case, at least), but it is usable with a little tweak.