feat: renamed Crx to crx. Added proxy support. Minor code improvements.

This commit is contained in:
Rick Rongen
2022-07-01 11:28:27 +02:00
parent 25bee5ee07
commit 305c1c9b31
10 changed files with 33 additions and 19 deletions

6
.gitignore vendored
View File

@@ -108,3 +108,9 @@ venv.bak/
# Idea
.idea/
*.iml
*.txt
!requirements.txt
*.csv
*.xlsx
scripts/

View File

@@ -2,7 +2,8 @@ import json
from typing import Union, List, Optional
from urllib.parse import urljoin
import requests
from requests import Session, Response
from requests.exceptions import RequestException
from .patchbuilder import PatchBuilder
from .simplenode import SimpleNode
@@ -57,7 +58,7 @@ class CrxException(ValueError):
class CrxNodeNotFound(CrxException):
def __init__(self, path: str, response: requests.Response):
def __init__(self, path: str, response: Response):
self.path = path
self.response = response
@@ -77,14 +78,14 @@ class Connection:
query: str = CRX_QUERY,
image_references: str = WCM_REFERENCES,
wcm_replicate: str = WCM_REPLICATE):
self._protocol = protocol
self._host = f'{protocol}://{host}:{port}'
self._data_root = self._host + root
self._query_path = self._host + query
self._image_references = self._host + image_references
self._wcm_replicate = self._host + wcm_replicate
self._session = requests.session()
self._session = Session()
self._patch_builder: Optional[PatchBuilder] = None
@@ -98,6 +99,12 @@ class Connection:
"""
self._session.auth = (username, password)
def proxy(self, proxy: str):
if proxy:
self._session.proxies[self._protocol] = proxy
elif self._session.proxies[self._protocol]:
del self._session.proxies[self._protocol]
def query(self, query: str, query_type: str = 'SQL2', raise_on_error: bool = True) -> List[str]:
"""
Perform an query and return the matching paths.
@@ -223,7 +230,7 @@ class Connection:
url = urljoin(self._data_root, '.' + path + JSON_DATA_EXTENSION)
try:
response = self._session.get(url)
except requests.exceptions.RequestException as exception:
except RequestException as exception:
raise CrxException() # todo more specific exceptions
if response.status_code == 404:

View File

@@ -1,12 +1,11 @@
from typing import Dict, List, Union
from typing import Dict, List, Union, TYPE_CHECKING
from logging import Logger
import json
if False:
if TYPE_CHECKING:
from .connection import Connection
from .simplenode import SimpleNode
LOGGER = Logger(__name__)
@@ -32,11 +31,13 @@ _patch_builders = {
class PatchBuilder:
changes: List[Dict]
dry_run: bool
def __init__(self, connection: 'Connection'):
self.connection = connection
self.changes = []
self.saved = False
self.dry_run = False
def set_value(self, path: str, value: Union[str, int, float], value_type: str):
self.changes.append({
@@ -51,7 +52,6 @@ class PatchBuilder:
'action': 'delete',
'path': path
})
pass
def save(self):
patch = []
@@ -62,7 +62,10 @@ class PatchBuilder:
LOGGER.warning("No patch to submit")
return
self.connection.apply_diff('\n'.join(patch))
if self.dry_run:
print('\n'.join(patch))
else:
self.connection.apply_diff('\n'.join(patch))
self.saved = True
def __enter__(self):

View File

@@ -1,6 +1,7 @@
from typing import TYPE_CHECKING
from logging import Logger
if False:
if TYPE_CHECKING:
from .connection import Connection
@@ -9,7 +10,7 @@ LOGGER = Logger(__name__)
class SimpleNode:
_normal_attrs = ['path', '_data', '_connection']
def __init__(self, path: str, data: dict, connection: 'Connection'):
self.path = path
self._data = data
@@ -63,6 +64,6 @@ class SimpleNode:
if isinstance(value, dict):
return self._connection.get_simple_node(self.path + '/' + item)
return value
def __dir__(self):
return super(SimpleNode, self).__dir__() + list(self._data.keys())

View File

@@ -1,4 +1,4 @@
from Crx import Connection, get_simple_con
from crx import Connection, get_simple_con
def main():

View File

@@ -1,5 +1,2 @@
requests >= 2.21.0
#lxml >= 4.3.0
# For unprotect function
# pywin32 >= 224
requests ~= 2.0
urllib3[socks] ~= 1.0