2017-03-07 16 views
3

我工作的組織開始使用Canvas LMS,我負責提取平臺的數據並幫助處理數據分析。如何使用python使用Canvas Data REST API?

Canvas LMS提供了一個Data API,但是我很難使用Python包裝器。我想用Python進行交互,這是我們官方堆棧的一部分。

我知道有官方文檔在(https://portal.inshosteddata.com/docs/api),但我真的不使用的授權方法和它會這麼容易有一個示例代碼。

那麼,我應該如何開始我的python代碼與Canvas LMS Data API進行交互?

回答

4

這裏我們開始吧!

我終於在Canvas社區的幫助下通過他們的網站完成了它(https://community.canvaslms.com/thread/7423)。我也在這裏發佈問題和答案,因爲我相信StackOverflow更容易找到答案。

希望這對其他人有用!

#!/usr/bin/python 

#imports 
import datetime 
import requests 
import hashlib 
import hmac 
import base64 
import json 


#Get the current time, printed in the right format 
def nowAsStr(): 
    currentTime = datetime.datetime.utcnow() 
    prettyTime = currentTime.strftime('%a, %d %b %Y %H:%M:%S GMT') 
    return prettyTime 

#Set up the request pieces 
apiKey = 'your_key' 
apiSecret = 'your_secret' 
method = 'GET' 
host = 'api.inshosteddata.com' 
path = '/api/account/self/dump' 
timestamp = nowAsStr() 

requestParts = [ 
    method, 
    host, 
    '', #content Type Header 
    '', #content MD5 Header 
    path, 
    '', #alpha-sorted Query Params 
    timestamp, 
    apiSecret 
] 

#Build the request 
requestMessage = '\n'.join(requestParts) 
print (requestMessage.__repr__()) 
hmacObject = hmac.new(apiSecret, '', hashlib.sha256) 
hmacObject.update(requestMessage) 
hmac_digest = hmacObject.digest() 
sig = base64.b64encode(hmac_digest) 
headerDict = { 
    'Authorization' : 'HMACAuth ' + apiKey + ':' + sig, 
    'Date' : timestamp 
} 

#Submit the request/get a response 
uri = "https://"+host+path 
print (uri) 
print (headerDict) 
response = requests.request(method='GET', url=uri, headers=headerDict, stream=True) 

#Check to make sure the request was ok 
if(response.status_code != 200): 
    print ('Request response went bad. Got back a ', response.status_code, ' code, meaning the request was ', response.reason) 
else: 
    #Use the downloaded data 
    jsonData = response.json() 
    print json.dumps(jsonData, indent=4)