Skip to content

Instantly share code, notes, and snippets.

Created December 28, 2012 13:08
Show Gist options
  • Save anonymous/4397666 to your computer and use it in GitHub Desktop.
Save anonymous/4397666 to your computer and use it in GitHub Desktop.
A very barebones api to pull and push data from a ravenhq instance Requires Requests ( http://www.python-requests.org/en/latest/ )
import logging, requests, simplejson
from datetime import datetime
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime) else None
def dumps(obj):
return simplejson.dumps(obj, use_decimal=True, default=dthandler)
l = logging.getLogger("ravendb")
class RavenDbOauthSession:
def __init__(self, base_url, api_key):
self.base_url = base_url
self.api_key = api_key
self._init = False
def request(self, url):
self._getOauthAccessData()
headers = {
'Authorization':"Bearer "+self._oauthData,
}
l.debug("GET "+url)
r = requests.get(self.base_url+"/"+url, headers=headers)
r.raise_for_status()
return r
def put(self, url_id, instance_type_name, instance_to_dump):
self._getOauthAccessData()
url = '%(base_url)s/docs/%(id)s' % dict(base_url=self.base_url, id=url_id)
headers = {
'Authorization':"Bearer "+self._oauthData,
'Raven-Entity-Name': instance_type_name,
}
l.debug("PUT "+url)
r = requests.put(url, data=dumps(instance_to_dump), headers=headers)
if(r.status_code != 201):
r.raise_for_status()
def _getOauthAccessData(self):
if self._init: return
l.debug("grabbing oauth code")
oauthUrl = "https://oauth.ravenhq.com/ApiKeys/OAuth/AccessToken"
headers = {
'content-type': 'application/json',
'accept': 'application/json;charset=UTF-8',
'grant_type': "client_credentials",
'Api-Key': self.api_key
}
rOauth = requests.get(oauthUrl, headers=headers)
if(rOauth.status_code != 200):
l.debug("Error getting ticket.")
l.debug("Headers : "+repr(rOauth.headers))
l.debug("Headers : "+repr(rOauth.content))
rOauth.raise_for_status()
self._oauthData = rOauth.content
self._init = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment