访问sf,记录下一下代码
(注册sf的app,登记 callback-url,执行sql查询)
#coding:utf-8
__author__ = 'scott'
import imp
imp.load_source('init','../init_script.py')
import urllib2,urllib,json,sys,os
import traceback,threading,time,struct,os,os.path,shutil,distutils.dir_util,array,base64,zlib,struct,binascii
import datetime
from libs.python.lemon import webapi
callback = 'http://localhost:8002/oauth'
client_id = '3MVG9ZL0ppGP5UrC_wQ8U02mOhowPKwjeaaLsWZ3BcYYVqiSsy1rL_D2h6qG.rGPnb_j6IcgLHPdhmvomzDFj'
client_secret = '9046731979xxxxxxx'
def accessToken(request,code,state):
url = 'https://login.salesforce.com/services/oauth2/token'
data = {
'grant_type':'authorization_code',
'code':code,
'client_id':client_id,
'client_secret':client_secret,
'redirect_uri':callback
}
result = ''
try:
result = urllib2.urlopen(url,urllib.urlencode(data) )
except:
traceback.print_exc()
result = result.read()
return json.loads( result )
def oauth(request):
cr = webapi.SuccCallReturn()
code = webapi.GET(request,'code','')
state = webapi.GET(request,'state','')
cr.result=[code,state]
token = accessToken(request,code,state)
cr.result.append(token)
print token
try:
sqlExecute(token['access_token'],token['instance_url'])
except:
traceback.print_exc()
return cr.httpResponse()
import cookielib
# -H "Authorization: OAuth token" -H "X-PrettyPrint:1" "
def sqlExecute(token,url_host):
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler, httpsHandler)
urllib2.install_opener(opener)
sf_cmd_query="%s/services/data/v20.0/query/?%s"%(url_host, urllib.urlencode({'q':'select count() from account'}))
headers = {
'Authorization':'OAuth %s'%token,
'X-PrettyPrint':1
}
httpReq = urllib2.Request( sf_cmd_query,headers=headers )
r = opener.open(httpReq).read()
print r
pass
url1 = """https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=%s&redirect_uri=%s&state=first"""%(client_id,callback)
def launchBrowserForOAuth():
import webbrowser
webbrowser.open(url1)
if __name__ == '__main__':
launchBrowserForOAuth()