Python calls Sina Weibo API project practices

Source: Internet
Author: User
Tags oauth
I recently came into contact with the project for calling the Sina Weibo open interface, so I want to use python to call the Weibo API. For more information, see the project for calling the Sina Weibo open interface recently, so I want to use python to call 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://api.weibo.com/oauth2/default.html '# Callback url authorization callback page, consistent with OAuth2.0 authorization settings USERID = ''# login Weibo user name, 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_access_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 content: 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 the token Token = client. request_access_token (code, REDIRECT_URL) save_access_token (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 The purpose is to execute apply_access_token () @ retry (1) def apply_access_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, expires_in) counter 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 Se Nd 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.