couchbeans 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,171 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.2
2
+ Name: couchbeans
3
+ Version: 0.0.1
4
+ Summary: A CouchDB library for python, focused on network resilience.
5
+ Author-email: Alex Baldwin <contact@alexbaldwin.dev>
6
+ License: LGPL-3.0
7
+ Project-URL: Homepage, https://github.com/owoalex/couchbeans
8
+ Project-URL: Issues, https://github.com/owoalex/couchbeans/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.4
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.28.0
15
+
16
+ # CouchBeans
17
+ *Have you ever held up a broken couch with a tin of beans?* CouchBeans is a [CouchDB](https://couchdb.apache.org/) library for python, aiming to provide as much resilience as possible for dodgy network environments. It's designed to be quick and easy to use, with as much complexity hidden from the user as possible.
18
+
19
+ A quick example:
20
+ ```
21
+ >>> from couchbeans import CouchClient
22
+ >>> db = CouchClient("http://root:couchbeans@localhost:6984/")
23
+ >>> db.get_document("main", "bb0065e5-d047-4bfc-b64a-855adeb89e35")
24
+ {"_id":"bb0065e5-d047-4bfc-b64a-855adeb89e35", "_rev": "1-90d3dbcd053542fda4bdd6754ecc917a", "msg": "hello world!"}
25
+ ```
26
+
27
+ Have a look at the [test script](./test/example.py) for more examples of how to use CouchBeans.
28
+
29
+ ## Installation
30
+ CouchBeans is installable via PIP:
31
+ ```pip install couchbeans```
32
+
33
+ ## Features
34
+ The main advantage of CouchBeans over other CouchDB libraries is its default handling of failed requests. CouchBeans will try a user-configurable number of times to execute a request to help with spotty network connections.
35
+
36
+ CouchBeans provides utility functions for modifying documents, including a patch operation. It also hides handling of the _rev parameter, making it easy to forget about the underlying network connections.
37
+
38
+ ## Dependencies
39
+
40
+ - requests
@@ -0,0 +1,25 @@
1
+ # CouchBeans
2
+ *Have you ever held up a broken couch with a tin of beans?* CouchBeans is a [CouchDB](https://couchdb.apache.org/) library for python, aiming to provide as much resilience as possible for dodgy network environments. It's designed to be quick and easy to use, with as much complexity hidden from the user as possible.
3
+
4
+ A quick example:
5
+ ```
6
+ >>> from couchbeans import CouchClient
7
+ >>> db = CouchClient("http://root:couchbeans@localhost:6984/")
8
+ >>> db.get_document("main", "bb0065e5-d047-4bfc-b64a-855adeb89e35")
9
+ {"_id":"bb0065e5-d047-4bfc-b64a-855adeb89e35", "_rev": "1-90d3dbcd053542fda4bdd6754ecc917a", "msg": "hello world!"}
10
+ ```
11
+
12
+ Have a look at the [test script](./test/example.py) for more examples of how to use CouchBeans.
13
+
14
+ ## Installation
15
+ CouchBeans is installable via PIP:
16
+ ```pip install couchbeans```
17
+
18
+ ## Features
19
+ The main advantage of CouchBeans over other CouchDB libraries is its default handling of failed requests. CouchBeans will try a user-configurable number of times to execute a request to help with spotty network connections.
20
+
21
+ CouchBeans provides utility functions for modifying documents, including a patch operation. It also hides handling of the _rev parameter, making it easy to forget about the underlying network connections.
22
+
23
+ ## Dependencies
24
+
25
+ - requests
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "couchbeans"
3
+ dynamic = ["version"]
4
+ authors = [
5
+ { name="Alex Baldwin", email="contact@alexbaldwin.dev" },
6
+ ]
7
+ license = { text="LGPL-3.0" }
8
+ description = "A CouchDB library for python, focused on network resilience."
9
+ readme = "README.md"
10
+ requires-python = ">=3.4"
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Operating System :: OS Independent",
14
+ ]
15
+ dependencies = [
16
+ "requests >= 2.28.0"
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/owoalex/couchbeans"
21
+ Issues = "https://github.com/owoalex/couchbeans/issues"
22
+
23
+ [tool.setuptools.dynamic]
24
+
25
+ [tool.setuptools]
26
+ packages = ["couchbeans"]
27
+ package-dir = {"" = "src"}
28
+
29
+ [tool.setuptools_scm]
30
+
31
+ [build-system]
32
+ requires = ["setuptools>=64", "setuptools-scm>=8"]
33
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+
2
+ from .client import CouchClient, HTTPMethod
3
+
@@ -0,0 +1,116 @@
1
+ import requests
2
+ from enum import Enum
3
+ from .exceptions import *
4
+
5
+ class HTTPMethod(Enum):
6
+ GET = 1
7
+ POST = 2
8
+ PUT = 3
9
+ DELETE = 4
10
+
11
+ class CouchClient:
12
+ __max_retries = 3
13
+ __connection_timeout = 3000
14
+ __verbose = False
15
+
16
+ def __init__(self, couch_base_uri):
17
+ if couch_base_uri.endswith("/"):
18
+ couch_base_uri = couch_base_uri[:-1]
19
+ self.__couch_base_uri = couch_base_uri
20
+ self.__current_session = requests.Session()
21
+
22
+ def get_server_version(self):
23
+ response = self.__couch_query("/", HTTPMethod.GET)
24
+ if "version" in response:
25
+ return response["version"]
26
+ return None
27
+
28
+ def set_verbose(self, verbose=True):
29
+ self.__verbose = verbose
30
+
31
+ def set_timeout(self, timeout):
32
+ self.__connection_timeout = timeout
33
+
34
+ def set_max_retries(self, max_retries):
35
+ self.__max_retries = max_retries
36
+
37
+ def __couch_query(self, endpoint, method, args = None):
38
+ try_n = 0
39
+ while try_n < self.__max_retries:
40
+ try:
41
+ if method == HTTPMethod.POST:
42
+ response = self.__current_session.post(self.__couch_base_uri + endpoint, json=args, timeout=self.__connection_timeout)
43
+ elif method == HTTPMethod.DELETE:
44
+ response = self.__current_session.delete(self.__couch_base_uri + endpoint, timeout=self.__connection_timeout)
45
+ elif method == HTTPMethod.PUT:
46
+ response = self.__current_session.put(self.__couch_base_uri + endpoint, json=args, timeout=self.__connection_timeout)
47
+ else:
48
+ response = self.__current_session.get(self.__couch_base_uri + endpoint, timeout=self.__connection_timeout)
49
+ if response.status_code >= 200 and response.status_code < 300:
50
+ return response.json()
51
+ else:
52
+ raise CouchHTTPError(response.json(), response.status_code)
53
+ except requests.exceptions.ConnectionError:
54
+ if self.__verbose:
55
+ print("Request (" + endpoint + ") was refused on try " + str(try_n))
56
+ try_n += 1
57
+ except requests.exceptions.Timeout:
58
+ if self.__verbose:
59
+ print("Request (" + endpoint + ") timed out on try " + str(try_n))
60
+ try_n += 1
61
+ raise ConnectionError("Gave up connecting to CouchDB after " + str(try_n) + " tries")
62
+
63
+ def find(self, database, selector = [], fields = None, sort = None, page = 0, page_size = 20):
64
+ for sortby in sort:
65
+ for key in sortby:
66
+ if not key in selector:
67
+ selector[key] = {"$exists": True}
68
+ mango = {
69
+ "selector": selector,
70
+ "skip": page * page_size,
71
+ "limit": page_size
72
+ }
73
+
74
+ if not sort is None:
75
+ mango["sort"] = sort
76
+
77
+ if not fields is None:
78
+ mango["fields"] = fields
79
+
80
+ return self.__couch_query("/" + database + "/_find", HTTPMethod.POST, mango)
81
+
82
+ def create_db(self, database, shards=None, replicas=None, partitioned=False):
83
+ options = {
84
+ "partitioned": bool(partitioned)
85
+ }
86
+ if not shards is None:
87
+ options["q"] = int(shards)
88
+ if not replicas is None:
89
+ options["n"] = int(replicas)
90
+ try:
91
+ self.__couch_query("/" + database, HTTPMethod.PUT, options)
92
+ return True
93
+ except CouchHTTPError as e:
94
+ if e.code == 412:
95
+ raise ObjectAlreadyExistsException("Database already exists", database)
96
+ raise e
97
+
98
+ def delete_db(self, database):
99
+ return self.__couch_query("/" + database, HTTPMethod.DELETE)
100
+
101
+ def get_document(self, database, doc_id):
102
+ return self.__couch_query("/" + database + "/" + str(doc_id), HTTPMethod.GET)
103
+
104
+ # This is a utility function - it will just delete whatever is at the ID!
105
+ def delete_document(self, database, doc_id):
106
+ document = self.__couch_query("/" + database + "/" + str(doc_id), HTTPMethod.GET)
107
+ return self.__couch_query("/" + database + "/" + str(doc_id) + "?rev=" + document["_rev"], HTTPMethod.DELETE)
108
+
109
+ def put_document(self, database, doc_id, document):
110
+ return self.__couch_query("/" + database + "/" + str(doc_id), HTTPMethod.PUT, document)
111
+
112
+ # Another utility function, will modify the document regardless of _rev
113
+ def patch_document(self, database, doc_id, document_diff):
114
+ document = self.__couch_query("/" + database + "/" + str(doc_id), HTTPMethod.GET)
115
+ merged_document = {**document, **document_diff}
116
+ return self.__couch_query("/" + database + "/" + str(doc_id), HTTPMethod.PUT, merged_document)
@@ -0,0 +1,17 @@
1
+ import json
2
+
3
+ class CouchHTTPError(Exception):
4
+ def __init__(self, body, code):
5
+ self.body = body
6
+ self.code = code
7
+
8
+ def __str__(self):
9
+ return "Error " + str(self.code) + " returned from CouchDB: " + json.dumps(self.body)
10
+
11
+ class ObjectAlreadyExistsException(Exception):
12
+ def __init__(self, message, obj_id):
13
+ self.message = message
14
+ self.obj_id = obj_id
15
+
16
+ def __str__(self):
17
+ return self.message
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.2
2
+ Name: couchbeans
3
+ Version: 0.0.1
4
+ Summary: A CouchDB library for python, focused on network resilience.
5
+ Author-email: Alex Baldwin <contact@alexbaldwin.dev>
6
+ License: LGPL-3.0
7
+ Project-URL: Homepage, https://github.com/owoalex/couchbeans
8
+ Project-URL: Issues, https://github.com/owoalex/couchbeans/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.4
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.28.0
15
+
16
+ # CouchBeans
17
+ *Have you ever held up a broken couch with a tin of beans?* CouchBeans is a [CouchDB](https://couchdb.apache.org/) library for python, aiming to provide as much resilience as possible for dodgy network environments. It's designed to be quick and easy to use, with as much complexity hidden from the user as possible.
18
+
19
+ A quick example:
20
+ ```
21
+ >>> from couchbeans import CouchClient
22
+ >>> db = CouchClient("http://root:couchbeans@localhost:6984/")
23
+ >>> db.get_document("main", "bb0065e5-d047-4bfc-b64a-855adeb89e35")
24
+ {"_id":"bb0065e5-d047-4bfc-b64a-855adeb89e35", "_rev": "1-90d3dbcd053542fda4bdd6754ecc917a", "msg": "hello world!"}
25
+ ```
26
+
27
+ Have a look at the [test script](./test/example.py) for more examples of how to use CouchBeans.
28
+
29
+ ## Installation
30
+ CouchBeans is installable via PIP:
31
+ ```pip install couchbeans```
32
+
33
+ ## Features
34
+ The main advantage of CouchBeans over other CouchDB libraries is its default handling of failed requests. CouchBeans will try a user-configurable number of times to execute a request to help with spotty network connections.
35
+
36
+ CouchBeans provides utility functions for modifying documents, including a patch operation. It also hides handling of the _rev parameter, making it easy to forget about the underlying network connections.
37
+
38
+ ## Dependencies
39
+
40
+ - requests
@@ -0,0 +1,14 @@
1
+ .gitignore
2
+ LICENSE
3
+ README.md
4
+ pyproject.toml
5
+ src/couchbeans/__init__.py
6
+ src/couchbeans/client.py
7
+ src/couchbeans/exceptions.py
8
+ src/couchbeans.egg-info/PKG-INFO
9
+ src/couchbeans.egg-info/SOURCES.txt
10
+ src/couchbeans.egg-info/dependency_links.txt
11
+ src/couchbeans.egg-info/requires.txt
12
+ src/couchbeans.egg-info/top_level.txt
13
+ test/couchbeans
14
+ test/example.py
@@ -0,0 +1 @@
1
+ requests>=2.28.0
@@ -0,0 +1 @@
1
+ couchbeans
@@ -0,0 +1,141 @@
1
+ #!/bin/python3
2
+
3
+ from couchbeans import CouchClient
4
+ from couchbeans.exceptions import ObjectAlreadyExistsException
5
+ import argparse
6
+ import json
7
+
8
+ def get_doc_diff(doc1, doc2):
9
+ if "_rev" in doc1: # These are very likely to be different, but not useful for most unit tests
10
+ del doc1["_rev"]
11
+ if "_rev" in doc2:
12
+ del doc2["_rev"]
13
+ if "_id" in doc1: # Also not that useful for testing
14
+ del doc1["_id"]
15
+ if "_id" in doc2:
16
+ del doc2["_id"]
17
+ set1 = set(doc1.items())
18
+ set2 = set(doc2.items())
19
+ diff = set2 ^ set1
20
+ return diff
21
+
22
+ def test_base_connection(conn, verbose):
23
+ if verbose:
24
+ print("Testing base connection")
25
+ if len(conn.get_server_version()) > 3:
26
+ return True
27
+ return False
28
+
29
+ def test_create_db(conn, verbose):
30
+ if verbose:
31
+ print("Testing db creation")
32
+ if conn.create_db("beans_test_db"):
33
+ return True
34
+ return False
35
+
36
+ def test_delete_db(conn, verbose):
37
+ if verbose:
38
+ print("Testing db deletion")
39
+ if conn.delete_db("beans_test_db"):
40
+ return True
41
+ return False
42
+
43
+ def test_put_document(conn, verbose):
44
+ if verbose:
45
+ print("Testing creating a document")
46
+ desired_doc = {
47
+ "edible": True,
48
+ "price": 1.20,
49
+ "weight": 500,
50
+ "stock": 256
51
+ }
52
+ conn.put_document("beans_test_db", "baked", desired_doc)
53
+ doc = conn.get_document("beans_test_db", "baked")
54
+ #print(json.dumps(doc, indent=4))
55
+ return len(get_doc_diff(doc, desired_doc)) == 0 # Check for an exact match
56
+
57
+ def test_patch_document(conn, verbose):
58
+ if verbose:
59
+ print("Testing patching the last document")
60
+ desired_doc = {
61
+ "edible": True,
62
+ "price": 1.20,
63
+ "weight": 500,
64
+ "stock": 255
65
+ } # This should be the state of the doc after the patch
66
+ patch = {
67
+ "stock": 255 # Someone's eaten some beans!
68
+ }
69
+ conn.patch_document("beans_test_db", "baked", patch)
70
+ doc = conn.get_document("beans_test_db", "baked")
71
+ #print(json.dumps(doc, indent=4))
72
+ return len(get_doc_diff(doc, desired_doc)) == 0 # Check for an exact match
73
+
74
+ def test_delete_document(conn, verbose):
75
+ if verbose:
76
+ print("Testing deleting the last document")
77
+ conn.delete_document("beans_test_db", "baked")
78
+ return True
79
+
80
+ if __name__ == "__main__":
81
+ parser = argparse.ArgumentParser(
82
+ prog="CouchBeans tester",
83
+ description="Tests the CouchBeans library, and acts as an example program")
84
+
85
+ parser.add_argument("connection_uri")
86
+ parser.add_argument("-v", "--verbose", action="store_true")
87
+ parser.add_argument("-j", "--json", action="store_true")
88
+
89
+ args = parser.parse_args()
90
+
91
+
92
+ as_json = args.json
93
+ verbose = args.verbose
94
+ if as_json:
95
+ verbose = False
96
+ couch_base_uri = args.connection_uri # e.g. http://root:couchbeans@localhost:5984/
97
+ conn = CouchClient(couch_base_uri)
98
+ conn.set_verbose(verbose)
99
+
100
+ passed_tests = []
101
+ failed_tests = []
102
+ exceptions = []
103
+ tests = [
104
+ test_base_connection,
105
+ test_create_db,
106
+ test_put_document,
107
+ test_patch_document,
108
+ test_delete_document,
109
+ test_delete_db,
110
+ ]
111
+
112
+ for test in tests:
113
+ try:
114
+ if test(conn, verbose):
115
+ passed_tests.append(test.__name__)
116
+ else:
117
+ failed_tests.append(test.__name__)
118
+ except Exception as e:
119
+ exceptions.append({
120
+ "on": test.__name__,
121
+ "error": str(e)
122
+ })
123
+
124
+ if as_json:
125
+ output = {
126
+ "passed": passed_tests,
127
+ "failed": failed_tests,
128
+ "crashed": exceptions
129
+ }
130
+ print(json.dumps(output, indent=4))
131
+ else:
132
+ print(f"{len(passed_tests)} tests passed")
133
+ for passt in passed_tests:
134
+ print(" - " + passt)
135
+ print(f"{len(failed_tests)} tests failed")
136
+ for failt in failed_tests:
137
+ print(" - " + failt)
138
+ print(f"{len(exceptions)} exceptions:")
139
+ for exception in exceptions:
140
+ print(" - " + exception["test"])
141
+ print(" " + exception["exception"])