Skip to content

Instantly share code, notes, and snippets.

@schuster-rainer
Created September 7, 2011 13:40
Show Gist options
  • Save schuster-rainer/1200587 to your computer and use it in GitHub Desktop.
Save schuster-rainer/1200587 to your computer and use it in GitHub Desktop.
ironpython access for the raven_db_http_api
import clr
from System.Net import WebRequest
from System.Text import ASCIIEncoding
from System.IO import StreamReader
def http(method, url, data_string=None, header={}):
request = WebRequest.Create(url)
request.UseDefaultCredentials = True
request.Method = method
if data_string:
request.ContentType = "application/x-www-form-urlencoded"
encoding = ASCIIEncoding()
data = encoding.GetBytes(data_string)
request.ContentLength = data.Length
stream = request.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()
for k,v in header.items():
request.Headers.Add(k,v)
response = request.GetResponse()
print response.StatusDescription
dataStream = response.GetResponseStream()
reader = StreamReader(dataStream)
responseFromServer = reader.ReadToEnd()
print responseFromServer
reader.Close()
dataStream.Close()
response.Close()
return responseFromServer
def save_entity(url, name, data_string):
return http("post", url, data_string, {"Raven-Entity-Name": name})
def record(name, data):
""" REVIEW: don't know if this will collide with different version or the scope"""
record_type = namedtuple(name, data.Keys)
record_instance = record_type(**data)
return record_instance
### SAMPLE USAGE ###
entity_name = "Person"
# save dictionary as ...
import json
person = {"name": "Rainer", "gender":"male"}
save_entity("http://localhost:8080/docs", entity_name, json.dumps(person))
# load some random person as dictionary
url = "http://localhost:8080/docs/%(entity)s/42" % {"entity":entity_name }
json_string = http("get", url)
data = json.loads(json_string)
# access some fields
print data['gender']
data['name'] = "somebody"
# create a namedtuple / record
# for some named tuple magic and how it works have a look at http://www.artima.com/weblogs/viewpost.jsp?thread=236637
raven_entity = record( entity_name, data)
#access fields
print raven_entity.name
print raven_entity
# READONLY: will fail
raven_entity.name = "Nobody"
# instead, create a new tuple
nobody = raven_entity._replace(name = "Nobody")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment