deepjson-py-connector 0.1.0__py3-none-any.whl

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,2 @@
1
+ from .client import DeepJSONConnector
2
+ from deepjson_py_connector import DeepJSONConnector
@@ -0,0 +1,179 @@
1
+ import requests
2
+ import platform
3
+ from typing import Any, Dict, Optional, Union
4
+ from requests_toolbelt.multipart.encoder import MultipartEncoder as FormData
5
+
6
+ class DeepJSONConnector:
7
+ def __init__(self, config: Dict[str, Any]):
8
+ self.base_url = config.get('base_url')
9
+ self.token = config.get('token')
10
+ self.storage = config.get('storage', 'memory')
11
+
12
+ # Transmission options
13
+ self.binary = False
14
+ self.overwrite_key = False
15
+ self.get_body = False
16
+
17
+ # Platform detection
18
+ self.is_node = platform.system() != "Emscripten"
19
+
20
+ # Configure session
21
+ self.session = requests.Session()
22
+ self.session.headers.update({
23
+ 'Accept': 'application/json',
24
+ 'User-Agent': 'DeepJSONConnector/1.0'
25
+ })
26
+ self.timeout = config.get('timeout', 10.0)
27
+
28
+ # Authentication methods
29
+ def login(self, username: str, password: str) -> Dict[str, Any]:
30
+ try:
31
+ response = self.session.post(
32
+ f"{self.base_url}/auth/login",
33
+ json={'username': username, 'password': password},
34
+ timeout=self.timeout
35
+ )
36
+ response.raise_for_status()
37
+ data = response.json()
38
+ self.token = data.get('token')
39
+ return data
40
+ except requests.RequestException as error:
41
+ self._handle_error(error)
42
+
43
+ def get_token(self) -> Optional[str]:
44
+ return self.token
45
+
46
+ def is_binary(self) -> bool:
47
+ return self.binary
48
+
49
+ def set_binary(self, true_or_false: bool) -> 'DeepJSONConnector':
50
+ self.binary = true_or_false
51
+ return self
52
+
53
+ def is_overwrite_key(self) -> bool:
54
+ return self.overwrite_key
55
+
56
+ def set_overwrite_key(self, true_or_false: bool) -> 'DeepJSONConnector':
57
+ self.overwrite_key = true_or_false
58
+ return self
59
+
60
+ def has_get_body(self) -> bool:
61
+ return self.get_body
62
+
63
+ def set_get_body(self, true_or_false: bool) -> 'DeepJSONConnector':
64
+ self.get_body = true_or_false
65
+ return self
66
+
67
+ # Core CRUD operations
68
+ def get(self, key: str, value: str = '') -> Any:
69
+ headers = {}
70
+ params = {}
71
+ http_method = "GET"
72
+ if self.get_body:
73
+ headers['X-Method-Override'] = "GET"
74
+ http_method = "POST"
75
+ if self.binary:
76
+ params['binary'] = True
77
+ # params['token'] = self.token
78
+ return self._request(http_method, f"/keys/{key}", params=params, data=value, headers=headers)
79
+
80
+ def post(self, key: str, value: Any) -> Any:
81
+ headers = {}
82
+ if self.overwrite_key:
83
+ headers['X-Override-Existing'] = 'true'
84
+ return self._request('POST', f"/keys/{key}", data=value, headers=headers)
85
+
86
+ def put(self, key: str, value: Any) -> Any:
87
+ headers = {}
88
+ return self._request('PUT', f"/keys/{key}", data=value, headers=headers)
89
+
90
+ def delete(self, key: str) -> Any:
91
+ headers = {}
92
+ return self._request('DELETE', f"/keys/{key}", headers=headers)
93
+
94
+ def move(self, key: str, params: Dict[str, Any], key_to: str) -> Any:
95
+ headers = {
96
+ 'X-Method-Override': "MOVE",
97
+ 'X-Move-Target': key_to
98
+ }
99
+ return self._request('POST', f"/keys/{key}", params=params, headers=headers)
100
+
101
+ # Universal file upload
102
+ def upload_file(self, key: str, file: Any, options: Dict[str, Any] = {}) -> Any:
103
+ if self.is_node:
104
+ # Node-like FormData handling
105
+ form = FormData(fields={
106
+ 'file': (file.name, file.stream(), 'application/octet-stream')
107
+ })
108
+ headers = {
109
+ 'Content-Type': form.content_type,
110
+ 'X-Override-Existing': 'true' if options.get('overwrite') else 'false'
111
+ }
112
+ else:
113
+ # Browser-like FormData handling
114
+ form = FormData()
115
+ form.append('file', file, file.name)
116
+ headers = {'X-Override-Existing': 'true' if options.get('overwrite') else 'false'}
117
+
118
+ return self._request('POST', f"/keys/{key}", data=form, headers=headers)
119
+
120
+ # Admin methods
121
+ def list_keys(self, filters: Dict[str, Any]) -> Any:
122
+ return self._request('GET', '/admin/keys', params=filters)
123
+
124
+ # Private methods
125
+ def _request(self, method: str, path: str, params: Optional[Dict] = None,
126
+ data: Any = None, headers: Optional[Dict] = None) -> Any:
127
+ try:
128
+ request_headers = {
129
+ **(headers or {}),
130
+ **({'Authorization': f"Bearer {self.token}"} if self.token else {})
131
+ }
132
+
133
+ # Handle FormData and content type
134
+ if isinstance(data, FormData):
135
+ request_headers.update({'Content-Type': data.content_type})
136
+ else:
137
+ request_headers["Content-Type"] = "text/plain; charset=utf-8"
138
+
139
+ # Prepare request
140
+ response = self.session.request(
141
+ method=method,
142
+ url=f"{self.base_url}{path}",
143
+ params=params or {},
144
+ data=data,
145
+ headers=request_headers,
146
+ timeout=self.timeout
147
+ )
148
+
149
+ response.raise_for_status()
150
+
151
+ if self.binary:
152
+ result = response.content
153
+ else:
154
+ result = response.json()
155
+
156
+ self._reset_flags()
157
+ return result
158
+
159
+ except requests.RequestException as error:
160
+ self._handle_error(error)
161
+
162
+ def _reset_flags(self):
163
+ self.binary = False
164
+ self.overwrite_key = False
165
+ self.get_body = False
166
+
167
+ def _handle_error(self, error: requests.RequestException):
168
+ if hasattr(error, 'response') and error.response:
169
+ err = Exception(f"API Error: {error.response.status_code} {error.response.reason}")
170
+ err.status = error.response.status_code
171
+ try:
172
+ err.details = error.response.json()
173
+ except ValueError:
174
+ err.details = error.response.text
175
+ raise err
176
+ elif isinstance(error, requests.ConnectionError):
177
+ raise Exception('Network Error: No response from server')
178
+ else:
179
+ raise Exception(f"Request Error: {str(error)}")
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: deepjson-py-connector
3
+ Version: 0.1.0
4
+ Summary: Python connector for DeepJSON server
5
+ Author-email: Eren Havuc <e.havuc@draykant.eu>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.7
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: requests>=2.25
11
+ Requires-Dist: requests-toolbelt>=0.9.1
12
+ Dynamic: license-file
13
+
14
+ # deepjson-py-connector
15
+
16
+ **A Python connector for interacting with DeepJSON, a flexible JSON document server for storage, scripting, and automation.**
17
+
18
+ ---
19
+
20
+ ## Features
21
+
22
+ - 🔐 Login with username/password and manage JWT tokens
23
+ - 📦 GET, POST, PUT, DELETE operations for keys
24
+ - 🖼️ Upload and move binary files (PDFs, images, etc.)
25
+ - 🧠 Scriptable value embedding using DeepJSON logic
26
+ - ⚙️ Works in sync mode with any DeepJSON backend
27
+ - ✅ Lightweight and dependency-friendly
28
+
29
+ ---
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install deepjson-py-connector
35
+ ```
36
+
37
+ ---
38
+
39
+ ## Usage
40
+
41
+ ```python
42
+ from deepjson_py_connector import DeepJSONConnector
43
+
44
+ client = DeepJSONConnector({
45
+ "base_url": "http://localhost:3000",
46
+ "token": "your-jwt-token"
47
+ })
48
+
49
+ # GET example
50
+ response = client.get("my-key")
51
+
52
+ # POST a JSON string
53
+ client.post("my-key", '{"name": "John"}')
54
+
55
+ # Upload a file
56
+ with open("receipt.pdf", "rb") as f:
57
+ client.upload_file("receipts/july", f)
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Flags & Options
63
+
64
+ Set optional flags before a request:
65
+
66
+ ```python
67
+ client.set_binary(True) # If you want binary content
68
+ client.set_get_body(True) # GET with body override
69
+ client.set_overwrite_key(True) # POST can overwrite if enabled
70
+ ```
71
+
72
+ All flags reset automatically after each request.
73
+
74
+ ---
75
+
76
+ ## Testing
77
+
78
+ Tests are written with `pytest`.
79
+
80
+ ```bash
81
+ pytest
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Project Structure
87
+
88
+ ```
89
+ deepjson_py_connector/
90
+ ├── __init__.py
91
+ ├── client.py # Main connector logic
92
+ ├── tests/
93
+ │ └── test_client.py
94
+ └── pyproject.toml
95
+ ```
96
+
97
+ ---
98
+
99
+ ## License
100
+
101
+ MIT © 2025 Eren Havuc
@@ -0,0 +1,7 @@
1
+ deepjson_py_connector/__init__.py,sha256=IzeSz8xbaZScZKsdBNXhxufprcLs1Auq6qbIut309bw,89
2
+ deepjson_py_connector/client.py,sha256=UBcpjtXu4GGTHU1X-hUzsk2cLT4l50myoeddRkB86To,6332
3
+ deepjson_py_connector-0.1.0.dist-info/licenses/LICENSE,sha256=bhiGUrcaWfuPvIHuFyW3f0YHT85SasWTkHExAkJrU5g,1067
4
+ deepjson_py_connector-0.1.0.dist-info/METADATA,sha256=6_JvY8Bq094zia2q4qyPYnyFjew4PqLBmXycxruQ4nM,1943
5
+ deepjson_py_connector-0.1.0.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
6
+ deepjson_py_connector-0.1.0.dist-info/top_level.txt,sha256=hkl73nV7b3N9YyTEtUTYnJ2I3rPm6S7SWxMORjhvuvU,22
7
+ deepjson_py_connector-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.7.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Eren Havuc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ deepjson_py_connector