Python calls Sina Weibo API project practices, pythonapi
I recently came into use to call the Sina Weibo open interface, so I would like to try using python to call the Weibo API.
SDK: http://open.weibo.com/wiki/SDK code is not more than a dozen K, can fully understand.
If you have a Weibo account, you can create an APP and then obtain the app key and app secret. This is required for the APP to obtain OAuth2.0 authorization.
For more information about oau2, see the description on Sina Weibo. In addition to the app key and app secret, the oau2's authorization parameter also requires the website callback address redirect_uri, And the callback address cannot be a LAN (which may not work for Shenma localhost or 127.0.0.1 ), this really worried me for a long time. I used APIs instead of website calls, so I checked a lot. We can see that someone can replace it with this address.
Let's take a look at a simple program:
Set the following parameters
import sysimport weiboimport webbrowserAPP_KEY = ''MY_APP_SECRET = ''REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'
Get the Weibo authorization URL, for example, line 1. After you open it in the default browser, you will be asked to log on to Weibo and log on with the account you want to authorize, as shown in figure
api = weibo.APIClient(app_key=APP_KEY,app_secret=MY_APP_SECRET,redirect_uri=REDIRECT_URL)authorize_url = api.get_authorize_url()print(authorize_url)webbrowser.open_new(authorize_url)
Will be transferred to a connection https://api.weibo.com/oauth2/default.html after login? Code = 92cc6accecfb5b2176adf58f4c
The key is the code value, which is the key to authentication. Manually enter the code value to simulate Authentication
request = api.request_access_token(code, REDIRECT_URL)access_token = request.access_tokenexpires_in = request.expires_inapi.set_access_token(access_token, expires_in)api.statuses.update.post(status=u'Test OAuth 2.0 Send a Weibo!')
Access_token is the obtained token, and expires_in is the authorization expiration time (UNIX time)
Use set_access_token to save the authorization. You can call the Weibo interface. Tested and sent a microblog
However, this manual code input method is not suitable for program calls. Do you need to open a link to request login for authorization? After searching and reference by multiple parties, the program is improved as follows, the code can be automatically obtained and saved to facilitate program service calls.
AccessWeibo #-*-coding: UTF-8-*-#/usr/bin/env python # access to SinaWeibo By sinaweibopy # automatically logs on to Weibo and generates tokens, save and update # suitable for backend service calls from weibo import APIClient import pymongo import sys, OS, urllib, urllib2 from http_helper import * from retry import * try: import json handle T ImportError: import simplejson as json # setting sys encoding to UTF-8 default_encoding = 'utf-8' if sys. getdefaultencoding ()! = Default_encoding: reload (sys) sys. setdefaultencoding (default_encoding) # weibo api access configuration APP_KEY = ''# app key APP_SECRET ='' # app secret REDIRECT_URL = 'https: // callback # callback url Authorization callback page, consistent with the authorization settings of OAuth2.0, USERID = ''# the user name for logging on to Weibo. It must be the test account USERPASSWD ='' set by OAuth2.0 # User Password client = APIClient (app_key = APP_KEY, app_secret = APP_SECRET, redirect_uri = REDIRECT_URL) def make_a Ccess_token (): # request access token params = urllib. urlencode ({'action': 'submit ', 'withofficalflag': '0', 'ticket': '', 'isloginsina ':'', 'response _ type ': 'code', 'regcallback': '', 'redirect _ url': REDIRECT_URL, 'client _ id': APP_KEY, 'state':'', 'from ': '', 'userid': userId, 'passwd': USERPASSWD,}) login_url = 'https: // api.weibo.com/oauth2/authorize' url = client. get_authorize_url () content = urllib2.urlopen (url) if cont Ent: headers = {'Referer': url} request = urllib2.Request (login_url, params, headers) opener = get_opener (False) urllib2.install _ opener (opener) try: f = opener. open (request) return_redirect_uri = f. url failed t urllib2.HTTPError, e: return_redirect_uri = e. geturl () # Get The Returned code = return_redirect_uri.split ('=') [1] # Get token = client. request_access_token (code, REDIRECT_URL) save_access_toke N (token) def save_access_token (token): # Save the access token to the MongoDB database mongoCon = pymongo. connection (host = "127.0.0.1", port = 27017) db = con. weibot = {"access_token": token ['Access _ token'], "expires_in": str (token ['expires _ in']), "date": time. strftime ('% Y-% m-% d % H: % M: % s', time. localtime (time. time ()} db. token. insert (t, safe = True) # Decorator is used to execute apply_access_token () again after make_access_token () @ retry (1) def apply_a Ccess_token (): # Read from MongoDB and set access token try: mongoCon = pymongo. connection (host = "127.0.0.1", port = 27017) db = con. weiboif db. token. count ()> 0: tokenInfos = db. token. find (). sort ([("_ id", pymongo. DESCENDING)]). limit (1) else: make_access_token () return False for tokenInfo in tokenInfos: access_token = tokenInfo ["access_token"] expires_in = tokenInfo ["expires_in"] try: client. set_access_token (access_token, expir Es_in) doesn t StandardError, e: if hasattr (e, 'error'): if e. error = 'Expired _ token': # generate make_access_token () return False else: pass token T: make_access_token () when the token expires () return False return True if _ name _ = "_ main _": apply_access_token () # The following is the application logic for accessing Weibo APIs # Use the publish text Weibo interface as an example client. statuses. update. post (status = 'test OAuth 2.0 Send a Weibo! ')
retry.pyimport mathimport time# Retry decorator with exponential backoffdef retry(tries, delay=1, backoff=2):"""Retries a function or method until it returns True.delay sets the initial delay, and backoff sets how much the delay shouldlengthen after each failure. backoff must be greater than 1, or else itisn't really a backoff. tries must be at least 0, and delay greater than0."""if backoff <= 1:raise ValueError("backoff must be greater than 1")tries = math.floor(tries)if tries < 0:raise ValueError("tries must be 0 or greater")if delay <= 0:raise ValueError("delay must be greater than 0")def deco_retry(f):def f_retry(*args, **kwargs):mtries, mdelay = tries, delay # make mutablerv = f(*args, **kwargs) # first attemptwhile mtries > 0:if rv == True or type(rv) == str: # Done on success ..return rvmtries -= 1 # consume an attempttime.sleep(mdelay) # wait...mdelay *= backoff # make future wait longerrv = f(*args, **kwargs) # Try againreturn False # Ran out of tries :-(return f_retry # true decorator -> decorated functionreturn deco_retry # @retry(arg[, ...]) -> true decorator
http_helper.py# -*- coding: utf-8 -*-#/usr/bin/env pythonimport urllib2,cookielibclass SmartRedirectHandler(urllib2.HTTPRedirectHandler):def http_error_301(cls, req, fp, code, msg, headers):result = urllib2.HTTPRedirectHandler.http_error_301(cls, req, fp, code, msg, headers)result.status = codeprint headersreturn resultdef http_error_302(cls, req, fp, code, msg, headers):result = urllib2.HTTPRedirectHandler.http_error_302(cls, req, fp, code, msg, headers)result.status = codeprint headersreturn resultdef get_cookie():cookies = cookielib.CookieJar()return urllib2.HTTPCookieProcessor(cookies)def get_opener(proxy=False):rv=urllib2.build_opener(get_cookie(), SmartRedirectHandler())rv.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]return rv
How to Use python to call Sina Weibo APIs
Compared with Twitter, Sina Weibo provides sdks directly (Twitter seems to only have third-party sdks ). I naturally use the Python SDK, a theme with only a few dozen k.
Then go to the exanples folder (SINA's English level, not mentioned ...), Opening the oauthSetTokenUpdate. py file is a standard example.
As a result, the following code is written:
View sourceprint? 01 #-*-coding: UTF-8 -*-
02
03 from weibopy. auth import OAuthHandler
04 from weibopy. api import API
05
06
07 consumer_key = 'application key'
08 consumer_secret = 'app secret'
09
10 auth = OAuthHandler (consumer_key, consumer_secret)
11 auth_url = auth. get_authorization_url ()
12 print 'Please authorize: '+ auth_url
13 verifier = raw_input ('pin: '). strip ()
14 auth. get_access_token (verifier)
15 api = API (auth)
16
17 status = api. update_status (status = 'Hello world', lat = '12. 3', long = '45. 6 ') # note that the status must be a UTF-8-encoded string, latitude and longitude can be not written
18 print status. id
19 print status. text
Note that consumer_key and consumer_secret must be created for an application to be obtained.
When you run this program, you will find that it has failed shamelessly and reports a syntax error:
File 'C: \ Documents and Settings \ Administrator \ Desktop \ sinatpy \ weibopy \ api. py ',
Line 197) (self, * args, post_data = post_data, headers = headers)
^ SyntaxError: invalid syntax open the weibopy \ api. py file and change row 197:
) (Self, post_data = post_data, headers = headers, * args)
When you run this program again, a URL link is displayed. You can open this link in your browser and grant the access permission. Then, you will get a string of PIN codes. After this PIN code is entered, a push message is sent, and the user's Access token key and Access token secret are displayed.
The whole process is very simple:
Use your consumer_key and consumer_secret to create an OAuthHandler object auth.
Instruct the user to access auth. get_authorization_url () and authorize the application.
Take ...... the remaining full text>
How does python call Sina Weibo api?
First download the Sina SDK, import the class, and then call the method to be called.