This repository has been archived by the owner on Oct 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcouchconnection.py
78 lines (63 loc) · 2.82 KB
/
couchconnection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import http.client
import base64
import json
import configreader
import sys
from distutils.version import LooseVersion as V
class CouchConnection(http.client.HTTPConnection):
"""docstring for CouchConnection"""
def __init__(self, host="127.0.0.1", port=5984, username="", password=""):
http.client.HTTPConnection.__init__(self, host, port)
self.username = username
self.password = password
def request(self, method, path, body="", header={}):
if self.username != "" and self.password != "":
creds = base64.encodestring(
('%s:%s' % (self.username, self.password)).encode()).decode().strip()
header["Authorization"] = "Basic %s" % creds
http.client.HTTPConnection.request(self, method, path, body, header)
def get(self, path, header={}):
self.request("GET", path, "", header)
return self.getresponse()
def post(self, path, body=None, header={}):
self.request("POST", path, body, header)
return self.getresponse()
def json_post(self, path, body=None, header={}):
h = {"Content-Type": "application/json"}
self.request("POST", path, body, dict(
list(h.items()) + list(header.items())))
return self.getresponse()
def put(self, path, body, header={}):
self.request("PUT", path, body, header)
return self.getresponse()
def json_put(self, path, body, header={}):
h = {"Content-Type": "application/json"}
self.request("PUT", path, body, dict(
list(h.items()) + list(header.items())))
return self.getresponse()
def delete(self, path, body=None, header={}):
self.request("GET", path)
res = self.getresponse()
doc = json.loads(res.read().decode('utf-8'))
if "_rev" in doc:
self.request("DELETE", path + "?rev=" + doc["_rev"], body, header)
res = self.getresponse()
return res.read()
else:
return False
def temp_view(self, path, body, header={}):
return self.json_post(path + "/_temp_view", body, header)
def temp_view_with_params(self, path, params, body, header={}):
return self.json_post(path + "/_temp_view" + params, body, header)
def require_legacy_couchdb_version(self):
self.request("GET", "/")
res = self.getresponse()
couchdb_info = json.loads(res.read().decode('utf-8'))
couchdb_version = V(couchdb_info["version"])
version_str = "2.0.0"
if couchdb_version >= V(version_str):
sys.exit("This script does not support CouchDB %s or newer." %
version_str)
def arsnova_connection(propertypath):
config = configreader.ConfigReader(propertypath)
return (config.dbName, CouchConnection(config.host, config.port, config.username, config.password))