Python calls Sina Weibo API project Practice _python

Source: Internet
Author: User
Tags mongodb oauth

Because of the recent exposure to a project that calls Sina Weibo's open interface, you want to try Python invoke the microblogging API.

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

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

Learn OAuth2 can view links to Sina Weibo's instructions. OAuth2 Authorization parameters In addition to the need for app key and app secret also need a Web site callback address Redirect_uri, and this callback address is not allowed to be lan (God horse localhost,127.0.0.1 seems to be no), this really makes me anxious for a long time. I use the API is not a Web site call, so I checked a lot. See someone write can use this address to replace, https://api.weibo.com/oauth2/default.html, I tried a bit really can, for cock silk is a good news.

Here is a simple procedure to feel:

Set the following parameters.

Import sys
import Weibo
import webbrowser

app_key = '
My_app_secret = '
redirect_url = ' https:// Api.weibo.com/oauth2/default.html '

Access to the micro-blog authorization URL, such as line 2nd, with the default browser opened will require landing microblogging, with the need to authorize the account login, as shown below

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, it will turn to a connection https://api.weibo.com/oauth2/default.html?code=92cc6accecfb5b2176adf58f4c

The key is the code value, which is the key to authentication. Manual input Code value simulation authentication

Request = Api.request_access_token (code, redirect_url)
Access_token = Request.access_token
expires_in = Request.expires_in
Api.set_access_token (Access_token, expires_in)
Api.statuses.update.post (status= U ' Test OAuth 2.0 Send a weibo! ')

Access_token is obtained token,expires_in is the Expiration Time (Unix time) of the authorization

Save authorization with Set_access_token. The micro-blogging interface can be invoked down. The test sent a micro blog

But such a manual input code, not suitable for the program call, whether you can not open the way to request access to the link to obtain authorization, through the multi-party search and reference, the program improved as follows, you can automatically get code and save to facilitate the program service calls.

Accessweibo #-*-coding:utf-8-*-#/usr/bin/env python #access to Sinaweibo by Sinaweibopy #实现微博自动登录, token automatically generated, saved and 
Update #适合于后端服务调用 from Weibo import apiclient import pymongo import sys. OS, urllib, urllib2 from http_helper import * 
From retry import * Try:import json except 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 microblogging username, must be OAuth2.0 set Test account userpasswd = ' # 
User Password client = apiclient (App_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 ': ', ' r Esponse_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 = Urllib 2.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 (req uest) Return_redirect_uri = F.url except Urllib2. Httperror, E:return_redirect_uri = E.geturl () # take to the returned code code = return_redirect_uri.split (' = ') [1] #得到token token = Client.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.weibo t={"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 perform a apply_access_token () @retry (1) def apply_access_token () once the Make_access_token () is invoked (): # Read and set access token Try:mongocon=pymongo from MongoDB. Connection (host= "127.0.0.1", port=27017) db= Mongocon.weibo if Db.token.count () >0:tokeninfos=db.token.find (). Sort ([("_id", Pymongo. Descending)]. Limit (1) else:make_access_token () return False to Tokeninfo in tokeninfos:access_token=tokeninfo["acc Ess_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 expired Regenerate Make_access_token () return Fals  

E else:pass except:make_access_token () return False return True if __name__ = = "__main__": Apply_access_token () # The following is the application logic for accessing the microblogging API # to post a text microblogging interface for example Client.statuses.update.post (status= ' Test OAuth 2.0 Send a weibo! ')

retry.py Import Math Import time # retry decorator with exponential Backoff def retry (tries, Delay=1, backoff=2): "" "Re

Tries a function or method until it returns TRUE. Delay sets the initial delay, and Backoff sets how much of the delay should after each lengthen. Backoff must be greater than 1, or else it isn ' t really a backoff.

Tries must is at least 0, and delay greater than 0. "" " If Backoff <= 1:raise valueerror ("Backoff must be greater than 1") tries = Math.floor (tries) if tries < 0:raise V Alueerror ("Tries must be 0 or greater") if delay <= 0:raise valueerror ("Delay must is greater than 0") def DECO_RETR
Y (f): Def f_retry (*args, **kwargs): mtries, Mdelay = tries, delay # make mutable RV = f (*args, **kwargs) # a attempt
While mtries > 0:if RV = = True or type (RV) = = str: # Done on success.  Return RV Mtries-= 1 # Consume a attempt time.sleep (mdelay) # wait ... mdelay *= Backoff # make future wait longer RV = F (*args, **kwargs) # Try again returN False # Ran out of tries:-(return F_retry # True decorator-> decorated function return Deco_retry # @retry (arg[, ...]) -> true Decorator

http_helper.py

#-*-coding:utf-8-*-
#/usr/bin/env python

import urllib2,cookielib

class 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 = code
Print Headers
return result

def http_error_302 (CLS, req, FP, code, MSG, headers): Result
= Urllib2. httpredirecthandler.http_error_302 (CLS, req, FP, code, MSG, headers)
result.status = code
Print Headers return result

def 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.