Skip to content

Instantly share code, notes, and snippets.

@davidreynolds
Created July 11, 2010 03:17
Show Gist options
  • Save davidreynolds/471247 to your computer and use it in GitHub Desktop.
Save davidreynolds/471247 to your computer and use it in GitHub Desktop.
import urllib2
from urllib import urlencode
class APIRequest(urllib2.Request):
"""
Hack urllib2.Request so we can use custom HTTP requests like DELETE and PUT
"""
def set_method(self, method):
self.method = method.upper()
def get_method(self):
return getattr(self, "method", urllib2.Request.get_method(self))
APIKEY = "YOUR_API_KEY"
APIURL = "http://formstore.alwaysmovefast.com"
def create_db(dbname):
"""
create a new database with `dbname`
Example:
create_db("testdb")
"""
data = urlencode({"dbname": dbname})
req = APIRequest(url="%s/v1/db" % APIURL,
data=data)
req.add_header("X-Formstore-Api-Key", APIKEY)
resp = urllib2.urlopen(req)
print resp.read()
def delete_db(dbname):
"""
deletes a database with name `dbname`
Example:
delete_db("testdb")
"""
req = APIRequest(url="%s/v1/db/%s" % (APIURL, dbname))
req.add_header("X-Formstore-Api-Key", APIKEY)
req.set_method("DELETE")
resp = urllib2.urlopen(req)
print resp.read()
def insert(dbname, **kwargs):
"""
`insert` urlencodes `kwargs` and inserts the data into `dbname`
Example:
insert("testdb", firstname="David", lastname="Reynolds")
"""
data = urlencode(kwargs)
req = APIRequest(url="%s/v1/db/%s" % (APIURL, dbname),
data=data)
req.add_header("X-Formstore-Api-Key", APIKEY)
resp = urllib2.urlopen(req)
print resp.read()
def get(dbname, key):
"""
Example:
get("testdb", "035a604d424247bca52724fe95882210")
"""
req = APIRequest(url="%s/v1/db/%s/%s" % (APIURL, dbname, key))
req.add_header("X-Formstore-Api-Key", APIKEY)
resp = urllib2.urlopen(req)
print resp.read()
def delete(dbname, key):
"""
Example:
delete("testdb", "035a604d424247bca52724fe95882210")
"""
req = APIRequest(url="%s/v1/db/%s/%s" % (APIURL, dbname, key))
req.add_header("X-Formstore-Api-Key", APIKEY)
req.set_method("DELETE")
resp = urllib2.urlopen(req)
print resp.read()
def update(dbname, key, **kwargs):
"""
Example:
update("testdb", "035a604d424247bca52724fe95882210", firstname="foo", lastname="bar")
"""
data = urlencode(kwargs)
req = APIRequest(url="%s/v1/db/%s/%s" % (APIURL, dbname, key),
data=data)
req.add_header("X-Formstore-Api-Key", APIKEY)
req.set_method("PUT")
resp = urllib2.urlopen(req)
print resp.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment