Created
May 14, 2013 22:45
-
-
Save Verurteilt/5580282 to your computer and use it in GitHub Desktop.
database.py
This file contains hidden or 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="localhost", port=5984): | |
| self.host = host | |
| self.port = port | |
| try: | |
| self.try_conectar = httplib.HTTPConnection(self.host, self.port) | |
| self.try_conectar.connect() | |
| print "Si esta conectado" | |
| except: | |
| print """You must turn on the couchdb server,if the couchdb | |
| server. is on, try changing the url""" | |
| def send(self, database="", username="", method="", data="", id="", password="", cb="", host="http://localhost", port=5984): | |
| if method.upper() == "GET": | |
| data = "" | |
| username = "" | |
| password = "" | |
| self.id = id | |
| self.host = host | |
| self.port = port | |
| self.database = database | |
| url = "%s:%d" % (self.host, self.port) | |
| url += "/%s/%s" % (self.database, self.id) | |
| request = urllib2.Request(url) | |
| contenido = urllib2.urlopen(request) | |
| contenido_dict = dict() | |
| for total in contenido: | |
| contenido_dict.update(json.loads(total)) | |
| exec "cb(contenido_dict)" | |
| return contenido_dict | |
| def create(self, username="", password="", database_name="couch_db"): | |
| self.host = host | |
| self.port = port | |
| if self.host.startswith('http://') or self.host.startswith('https://'): | |
| self.host = host | |
| else: | |
| self.host = "http://%s" % self.host | |
| self.database_name = database_name | |
| self.username = username | |
| self.password = password | |
| try: | |
| opener = urllib2.build_opener(urllib2.HTTPHandler) | |
| url = "%s:%d/%s" % (self.host, self.port, self.database_name) | |
| print "Creating database %s on %s" % (self.database_name, url) | |
| request = urllib2.Request(url) | |
| if self.username != "" and self.password != "": | |
| base64string = base64.encodestring('%s:%s' % (self.username, self.password)).replace('\n', '') | |
| request.add_header('Authorization', 'Basic %s' % base64string) | |
| request.get_method = lambda: "PUT" | |
| self.uri = opener.open(request) | |
| print "Time to relax." | |
| except: | |
| print """Ooop Something was wrong, verify the username, | |
| password, host, and port""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment