Skip to content

Instantly share code, notes, and snippets.

@Verurteilt
Last active December 17, 2015 07:19
Show Gist options
  • Save Verurteilt/5572001 to your computer and use it in GitHub Desktop.
Save Verurteilt/5572001 to your computer and use it in GitHub Desktop.
CouchDb client in process
import base64
import urllib2
import json
import httplib
class CouchDatabase(object):
def __init__(self,host="http://localhost", port=5984):
self.host =host
self.port = port
if self.host.startswith("http://") or self.host.startswith("https://"):
pass
else:
self.host = "http://%s"% self.host
try:
self.try_conectar = httplib.HTTPConnection(host,port)
self.try_conectar.connect()
except:
print "You must turn on the couchdb server, if the couchdb server is on, try changing the url"
def create(self, database_name="couch_db",host="http://localhost", port=5984, username, password):
self.host =host
self.port = port
self.database_name = database_name
self.username = username
self.password = password
if self.host.startswith("http://") or self.host.startswith("https://"):
pass
try:
opener = urllib2.build_opener(urllib2.HTTPHandler)
url="%s:%d/%s"%(self.host,self.port,self.database_name)
request = urllib2.Request(url)
login = base64.b64encode("%s:%s")%(self.username,self.password)
request.add_header('Authorization','Basic '+str(login))
request.get_method= lambda: "PUT"
todo = opener.open(request)
print "Time to relax."
except:
print "Ooop Something was wrong, verify the username, password, host, and port"
class CouchDocument(object):
def __init__(self,host="http://localhost", port=5984, databse=""):
self.host =host
self.port = port
self.database = database
if self.host.startswith("http://") or self.host.startswith("https://"):
pass
else:
self.host = "http://%s"% self.host
try:
self.try_conectar = httplib.HTTPConnection(host,port)
self.try_conectar.connect()
except:
print "You must turn on the couchdb server, if the couchdb server is on, try changing the url"
def get(self, cb="", id):
self.id = id
opener = urllib2.build_opener(urllib2.HTTPHandler)
url+="/%s/%s"%(self.database, self.id)
request = urllib2.Request(url)
contenido = urllib2.urlopen(request)
exec "cb(contenido)"
return contenido
def cb(parameter):
for i in parameter:
print i
x=CouchDb()
x.get(cb=cb, id="someId123")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment