如何使用python使用canvasdatarestapi?

2024-09-28 05:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我工作的组织开始使用Canvas LMS,我负责提取平台的数据,并帮助进行数据洞察。在

Canvas LMS提供了一个数据API,这很好,但是我很难让Python包装器使用。我想用Python与它交互,Python是我们这里的官方堆栈的一部分。在

我知道(https://portal.inshosteddata.com/docs/api)中有官方文档,但我并没有真正使用授权方法,因此有一个示例代码会容易得多。在

那么,我应该如何启动python代码来与Canvas LMS数据API交互呢?在


Tags: 数据代码httpscomapidocs官方堆栈
1条回答
网友
1楼 · 发布于 2024-09-28 05:22:38

开始了!在

在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)

相关问题 更多 >

    热门问题