laser4you Oja, ich habe mich auch darüber geärgert! Siehe weiterentwicklung-api. Ich würde nicht da "herumbasteln", sondern standard python libraries verwenden. Beim XML ist auch was nicht sauber. So habe ich es gelöst:
import json
import requests
import dicttoxml
from requests.auth import HTTPBasicAuth
from xml.etree import ElementTree
# Helpers
@staticmethod
def dict_to_xml_values(dictionary):
'''e.g. data_dict = {
"de": "cust_color",
"en": "cust_color",
"fr": "cust_color",
"it": "cust_color"
}
returns <values><de>cust_color</de><en>cust_color</en><fr>cust_color</fr><it>cust_color</it></values>
'''
if dictionary:
# add values as key
data = dict(values=dictionary)
# Convert dictionary to XML
xml_str = dicttoxml.dicttoxml(data, custom_root='root', attr_type=False)
# Parse the XML string
root = ElementTree.fromstring(xml_str)
# Find the 'values' element and convert it back to a string
values_element = root.find('values')
xml_bytes = ElementTree.tostring(values_element, encoding=ENCODING)
# Decode bytes to string
xml_string = xml_bytes.decode(ENCODING)
else:
xml_string = ''
return xml_string
@staticmethod
def xml_values_to_dict(xml_str):
'''e.g. xml_str = "<values><de>cust_color</de><en>cust_color</en><fr>cust_color</fr><it>cust_color</it></values>"
returns {
"de": "cust_color",
"en": "cust_color",
"fr": "cust_color",
"it": "cust_color"
}
'''
if xml_str:
# Parse the XML string
root = ElementTree.fromstring(xml_str)
# Convert XML to dictionary
return {child.tag: child.text for child in root}
else:
return {}
# Function to get a person
def get_person(self, id):
# Get data
url = f'{self.base}/person/read.json'
params = {'id': id}
response = requests.get(url, params=params, auth=self.auth)
person_data = response.json()['data']
# Repair custom
self.convert_custom_xml_to_dict(person_data, FIELD_TYPE.PERSON.value)
return person_data
# Function to create a person
def _post_person_data(self, person_data, action):
'''action is create or update
'''
# Convert jsons as API only takes str, not JSON
for key in ['addresses', 'contacts']:
person_data[key] = json.dumps(person_data.get(key))
# Convert 'custom' field to XML if any
if 'custom' in person_data:
# Get existing fields
person_data['custom'] = self.convert_custom_dict_to_xml(
person_data.pop('custom'), FIELD_TYPE.PERSON.value)
# Post
url = f'{self.base}/person/{action}.json'
response = requests.post(url, data=person_data, auth=self.auth)
return response.json()
Hoffe auf eine v2 API, sonst werde ich mal einen Wrapper in git erstellen.