Python calls Sina Weibo API project practice

Source: Internet
Author: User
Since I recently contacted a project that calls the Sina Weibo open interface, I wanted to try Python to invoke the microblog API.

SDK Download Address: Http://open.weibo.com/wiki/SDK code is not more than more than 10 k, can be fully understood.

With a Weibo account you can create a new app and then get app key and app secret, which is required for the app to get OAuth2.0 authorization.

Learn about OAuth2 to see a description of the link to Sina Weibo. OAuth2 Authorization parameters In addition to the need for app key and app secret also need site callback address Redirect_uri, and this callback address is not allowed to LAN (God Horse localhost,127.0.0.1 seems to be not), this really makes me anxious for a long day. I use the API is not a site call, so looked a lot. See someone write can be replaced with this address, https://api.weibo.com/oauth2/default.html, I tried a bit sure enough, for the cock silk is a good news.

Let's start with a simple program to get a feel for yourself:

Set the following parameters.

Import sysimport Weiboimport Webbrowserapp_key = ' My_app_secret = ' Redirect_url = ' https://api.weibo.com/oauth2/ Default.html '

Access to the Weibo license URL, such as line 2nd, will be required to log on to Weibo when opened with the default browser, such as

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)

After landing will be reversed to a connection https://api.weibo.com/oauth2/default.html?code=92cc6accecfb5b2176adf58f4c

The key is the code value, which is the key to certification. Manually enter code value simulation 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,expires_in is the expiration time of the authorization (Unix time)

Save the authorization with Set_access_token. You can call the Micro-blog interface down. The test sent a Weibo message

However, the manual input code method, is not suitable for the application of the call, whether you can not open the link to request login to obtain authorization, through the multi-party lookup and reference, the program is improved as follows, you can achieve automatic access to code and save, convenient program service invocation.

accessweibo#-*-coding:utf-8-*-#/usr/bin/env python #access to Sinaweibo by Sinaweibopy #实现微博自动登录, token is automatically generated, saved and updated #适合于 Backend service call from Weibo import apiclient import pymongo import sys, OS, urllib, urllib2 from http_helper import * from retry Imp ORT * Try:import JSON except Importerror:import Simplejson as JSON # setting SYS encoding to utf-8 default_encoding = ' u Tf-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 ' # C Allback URL Authorization callback page, consistent with OAuth2.0 authorization settings, USERID = "# login Weibo username, must be OAuth2.0 set Test account userpasswd = ' # user Password client = apiclient (a Pp_key=app_key, App_secret=app_secret, Redirect_uri=redirect_url) def make_access_token (): #请求access token params = Urllib.urlencode ({' Action ': ' Submit ', ' Withofficalflag ': ' 0 ', ' ticket ': ', ' Isloginsina ': ', ' response_type ': ' Code ', ' Regcallback ': ', ' Redirect_uri ': 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 except Urllib2. Httperror, E:return_redirect_uri = E.geturl () # takes the returned code code = return_redirect_uri.split (' = ') [1] #得到token token = Clien T.request_access_token (Code,redirect_url) Save_access_token (token) def save_access_token (token): #将access Token is saved to the MongoDB database Mongocon=pymongo. Connection (host= "127.0.0.1", port=27017) db= mongocon.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 purpose is to execute once after calling Make_access_token () Apply_access_token () @retry (1) def apply_access_token (): #从MongoDB读取及设置access token Try:mongocon=pymongo. Connection (host= "127.0.0.1", port=27017) db= mongocon.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) except StandardError, E:if hasattr (E, ' error '): if e.error = = ' Expired_token ': # token expires regenerate Make_access_token () return False Els E:pass Except:make_access_token () return False return True if __name__ = = "__main__": Apply_access_token () # Below is the access to the Weibo API Use logical # To publish a text microblogging interface for 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 is 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 Valuee Rror ("Tries must is 0 or greater") if delay <= 0:raise valueerror ("Delay must be greater than 0") def deco_retry (f):d EF F _retry (*args, **kwargs): mtries, Mdelay = tries, delay # make mutablerv = f (*args, **kwargs) # first Attemptwhile mtries &G T 0:if RV = = True or type (RV) = = str: # Done on success. return rvmtries-= 1 # consume an attempttime.sleep (mdelay) # Wait...mdelay *= Backoff # Make a future wait LONGERRV = f (*ar GS, **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):d EF 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.