Last active
December 17, 2015 07:19
-
-
Save Verurteilt/5572001 to your computer and use it in GitHub Desktop.
CouchDb client in process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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