repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.getEndpointSubscriptions
|
python
|
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
|
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L394-L414
|
[
"def _getURL(self, url,query={},versioned=True):\n\tif versioned:\n\t\treturn r.get(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n\telse:\n\t\treturn r.get(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n"
] |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.getResourceSubscription
|
python
|
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
|
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L418-L440
|
[
"def _getURL(self, url,query={},versioned=True):\n\tif versioned:\n\t\treturn r.get(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n\telse:\n\t\treturn r.get(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n"
] |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.putPreSubscription
|
python
|
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
|
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L442-L467
|
[
"def _putURL(self, url,payload=None,versioned=True):\n\tif self._isJSON(payload):\n\t\tself.log.debug(\"PUT payload is json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\telse:\n\t\tself.log.debug(\"PUT payload is NOT json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,data=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,data=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n",
"def _isJSON(self,dataIn):\n\ttry:\n\t\tjson.dumps(dataIn)\n\t\treturn True\n\texcept:\n\t\tself.log.debug(\"[_isJSON] exception triggered, input is not json\")\n\t\treturn False\n"
] |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.getPreSubscription
|
python
|
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
|
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L469-L487
|
[
"def _getURL(self, url,query={},versioned=True):\n\tif versioned:\n\t\treturn r.get(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n\telse:\n\t\treturn r.get(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n"
] |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.putCallback
|
python
|
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
|
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L489-L513
|
[
"def _putURL(self, url,payload=None,versioned=True):\n\tif self._isJSON(payload):\n\t\tself.log.debug(\"PUT payload is json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\telse:\n\t\tself.log.debug(\"PUT payload is NOT json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,data=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,data=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n"
] |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.setHandler
|
python
|
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
|
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L554-L583
| null |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.startLongPolling
|
python
|
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread
|
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L587-L608
| null |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.stopLongPolling
|
python
|
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
|
Stop LongPolling thread
:return: none
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L611-L622
| null |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.handler
|
python
|
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
|
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L648-L685
| null |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
ARMmbed/mbed-connector-api-python
|
mbed_connector_api/mbed_connector_api.py
|
connector.debug
|
python
|
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
|
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
|
train
|
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L688-L715
| null |
class connector:
"""
Interface class to use the connector.mbed.com REST API.
This class will by default handle asyncronous events.
All function return :class:'.asyncResult' objects
"""
# Return connector version number and recent rest API version number it supports
def getConnectorVersion(self):
"""
GET the current Connector version.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_mdc_version",data.status_code)
result.is_done = True
return result
# Return API version of connector
def getApiVersions(self):
"""
Get the REST API versions that connector accepts.
:returns: :class:asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/rest-versions",versioned=False)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_rest_version",data.status_code)
result.is_done = True
return result
# Returns metadata about connector limits as JSON blob
def getLimits(self):
"""return limits of account in async result object.
:returns: asyncResult object, populates error and result fields
:rtype: asyncResult
"""
result = asyncResult()
data = self._getURL("/limits")
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("limit",data.status_code)
result.is_done = True
return result
# return json list of all endpoints.
# optional type field can be used to match all endpoints of a certain type.
def getEndpoints(self,typeOfEndpoint=""):
"""
Get list of all endpoints on the domain.
:param str typeOfEndpoint: Optional filter endpoints returned by type
:return: list of all endpoints
:rtype: asyncResult
"""
q = {}
result = asyncResult()
if typeOfEndpoint:
q['type'] = typeOfEndpoint
result.extra['type'] = typeOfEndpoint
data = self._getURL("/endpoints", query = q)
result.fill(data)
if data.status_code == 200:
result.error = False
else:
result.error = response_codes("get_endpoints",data.status_code)
result.is_done = True
return result
# return json list of all resources on an endpoint
def getResources(self,ep,noResp=False,cacheOnly=False):
"""
Get list of resources on an endpoint.
:param str ep: Endpoint to get the resources of
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: list of resources
:rtype: asyncResult
"""
# load query params if set to other than defaults
q = {}
result = asyncResult()
result.endpoint = ep
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
self.log.debug("ep = %s, query=%s",ep,q)
data = self._getURL("/endpoints/"+ep, query=q)
result.fill(data)
# check sucess of call
if data.status_code == 200: # sucess
result.error = False
self.log.debug("getResources sucess, status_code = `%s`, content = `%s`", str(data.status_code),data.content)
else: # fail
result.error = response_codes("get_resources",data.status_code)
self.log.debug("getResources failed with error code `%s`" %str(data.status_code))
result.is_done = True
return result
# return async object
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - specify no response necessary from endpoint
:param bool cacheOnly: Optional - get results from cache on connector, do not wake up endpoint
:return: value of the resource, usually a string
:rtype: asyncResult
"""
q = {}
result = asyncResult(callback=cbfn) #set callback fn for use in async handler
result.endpoint = ep
result.resource = res
if noResp or cacheOnly:
q['noResp'] = 'true' if noResp == True else 'false'
q['cacheOnly'] = 'true' if cacheOnly == True else 'false'
# make query
data = self._getURL("/endpoints/"+ep+res, query=q)
result.fill(data)
if data.status_code == 200: # immediate success
result.error = False
result.is_done = True
if cbfn:
cbfn(result)
return result
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else: # fail
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
"""
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/endpoints/"+ep+res,payload=data)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
#return async object
def postResource(self,ep,res,data="",cbfn=""):
'''
POST data to a resource on an endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param str data: Optional - data to send via POST
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._postURL("/endpoints/"+ep+res,data)
if data.status_code == 201: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
def deleteEndpoint(self,ep,cbfn=""):
'''
Send DELETE message to an endpoint.
:param str ep: name of endpoint
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
data = self._deleteURL("/endpoints/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("resource",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# subscribe to endpoint/resource, the cbfn is given an asynch object that
# represents the result. it is up to the user to impliment the notification
# channel callback in a higher level library.
def putResourceSubscription(self,ep,res,cbfn=""):
'''
Subscribe to changes in a specific resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult(callback=cbfn)
result.endpoint = ep
result.resource = res
data = self._putURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
elif data.status_code == 202:
self.database['async-responses'][json.loads(data.content)["async-response-id"]]= result
else:
result.error = response_codes("subscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteEndpointSubscriptions(self,ep):
'''
Delete all subscriptions on specified endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._deleteURL("/subscriptions/"+ep)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("delete_endpoint_subscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteResourceSubscription(self,ep,res):
'''
Delete subscription to a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._deleteURL("/subscriptions/"+ep+res)
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def deleteAllSubscriptions(self):
'''
Delete all subscriptions on the domain (all endpoints, all resources)
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/subscriptions/")
if data.status_code == 204: #immediate success
result.error = False
result.is_done = True
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getEndpointSubscriptions(self,ep):
'''
Get list of all subscriptions on a given endpoint ``ep``
:param str ep: name of endpoint
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
data = self._getURL("/subscriptions/"+ep)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
# return async object
# result field is a string
def getResourceSubscription(self,ep,res):
'''
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep``
:param str ep: name of endpoint
:param str res: name of resource
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
result.endpoint = ep
result.resource = res
data = self._getURL("/subscriptions/"+ep+res)
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.content
else:
result.error = response_codes("unsubscribe",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putPreSubscription(self,JSONdata):
'''
Set pre-subscription rules for all endpoints / resources on the domain.
This can be useful for all current and future endpoints/resources.
:param json JSONdata: data to use as pre-subscription data. Wildcards are permitted
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
if isinstance(JSONdata,str) and self._isJSON(JSONdata):
self.log.warn("pre-subscription data was a string, converting to a list : %s",JSONdata)
JSONdata = json.loads(JSONdata) # convert json string to list
if not (isinstance(JSONdata,list) and self._isJSON(JSONdata)):
self.log.error("pre-subscription data is not valid. Please make sure it is a valid JSON list")
result = asyncResult()
data = self._putURL("/subscriptions",JSONdata, versioned=False)
if data.status_code == 204: # immediate success with no response
result.error = False
result.is_done = True
result.result = []
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def getPreSubscription(self):
'''
Get the current pre-subscription data from connector
:return: JSON that represents the pre-subscription data in the ``.result`` field
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/subscriptions")
if data.status_code == 200: #immediate success
result.error = False
result.is_done = True
result.result = data.json()
else:
result.error = response_codes("presubscription",data.status_code)
result.is_done = True
result.raw_data = data.content
result.status_code = data.status_code
return result
def putCallback(self,url,headers=""):
'''
Set the callback URL. To be used in place of LongPolling when deploying a webapp.
**note**: make sure you set up a callback URL in your web app
:param str url: complete url, including port, where the callback url is located
:param str headers: Optional - Headers to have Connector send back with all calls
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
payloadToSend = {"url":url}
if headers:
payload['headers':headers]
data = self._putURL(url="/notification/callback",payload=payloadToSend, versioned=False)
if data.status_code == 204: #immediate success
result.error = False
result.result = data.content
else:
result.error = response_codes("put_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def getCallback(self):
'''
Get the callback URL currently registered with Connector.
:return: callback url in ``.result``, error if applicable in ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._getURL("/notification/callback",versioned=False)
if data.status_code == 200: #immediate success
result.error = False
result.result = data.json()
else:
result.error = response_codes("get_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
def deleteCallback(self):
'''
Delete the Callback URL currently registered with Connector.
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rtype: asyncResult
'''
result = asyncResult()
data = self._deleteURL("/notification/callback")
if data.status_code == 204: #immediate success
result.result = data.content
result.error = False
else:
result.error = response_codes("delete_callback_url",data.status_code)
result.raw_data = data.content
result.status_code = data.status_code
result.is_done = True
return result
# set a specific handler to call the cbfn
def setHandler(self,handler,cbfn):
'''
Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cbfn: function to pass the notification channel messages to.
:return: Nothing.
'''
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registrations":
self.de_registrations_callback = cbfn
elif handler == "reg-updates":
self.reg_updates_callback = cbfn
elif handler == "registrations":
self.registrations_callback = cbfn
elif handler == "notifications":
self.notifications_callback = cbfn
else:
self.log.warn("'%s' is not a legitimate notification channel option. Please check your spelling.",handler)
# this function needs to spin off a thread that is constantally polling,
# should match asynch ID's to values and call their function
def startLongPolling(self, noWait=False):
'''
Start LongPolling Connector for notifications.
:param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond
:return: Thread of constantly running LongPoll. To be used to kill the thred if necessary.
:rtype: pythonThread
'''
# check Asynch ID's against insternal database of ID's
# Call return function with the value given, maybe decode from base64?
wait = ''
if(noWait == True):
wait = "?noWait=true"
# check that there isn't another thread already running, only one longPolling instance per is acceptable
if(self.longPollThread.isAlive()):
self.log.warn("LongPolling is already active.")
else:
# start infinite longpolling thread
self._stopLongPolling.clear()
self.longPollThread.start()
self.log.info("Spun off LongPolling thread")
return self.longPollThread # return thread instance so user can manually intervene if necessary
# stop longpolling by switching the flag off.
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return
# Thread to constantly long poll connector and process the feedback.
# TODO: pass wait / noWait on to long polling thread, currently the user can set it but it doesnt actually affect anything.
def longPoll(self, versioned=True):
self.log.debug("LongPolling Started, self.address = %s" %self.address)
while(not self._stopLongPolling.is_set()):
try:
if versioned:
data = r.get(self.address+self.apiVersion+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
else:
data = r.get(self.address+'/notification/pull',headers={"Authorization":"Bearer "+self.bearer,"Connection":"keep-alive","accept":"application/json"})
self.log.debug("Longpoll Returned, len = %d, statuscode=%d",len(data.text),data.status_code)
# process callbacks
if data.status_code == 200: # 204 means no content, do nothing
self.handler(data.content)
self.log.debug("Longpoll data = "+data.content)
except:
self.log.error("longPolling had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
self.log.info("Killing Longpolling Thread")
# parse the notification channel responses and call appropriate handlers
def handler(self,data):
'''
Function to handle notification data as part of Callback URL handler.
:param str data: data posted to Callback URL by connector.
:return: nothing
'''
if isinstance(data,r.models.Response):
self.log.debug("data is request object = %s", str(data.content))
data = data.content
elif isinstance(data,str):
self.log.info("data is json string with len %d",len(data))
if len(data) == 0:
self.log.warn("Handler received data of 0 length, exiting handler.")
return
else:
self.log.error("Input is not valid request object or json string : %s" %str(data))
return False
try:
data = json.loads(data)
if 'async-responses' in data.keys():
self.async_responses_callback(data)
if 'notifications' in data.keys():
self.notifications_callback(data)
if 'registrations' in data.keys():
self.registrations_callback(data)
if 'reg-updates' in data.keys():
self.reg_updates_callback(data)
if 'de-registrations' in data.keys():
self.de_registrations_callback(data)
if 'registrations-expired' in data.keys():
self.registrations_expired_callback(data)
except:
self.log.error("handle router had an issue and threw an exception")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
# Turn on / off debug messages based on the onOff variable
def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level == "INFO":
self.log.setLevel(logging.INFO)
self._ch.setLevel(logging.INFO)
self.log.info("Debugging level INFO enabled")
elif level == "WARN":
self.log.setLevel(logging.WARN)
self._ch.setLevel(logging.WARN)
self.log.warn("Debugging level WARN enabled")
elif level == "ERROR":
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Debugging level ERROR enabled")
else:
self.log.setLevel(logging.ERROR)
self._ch.setLevel(logging.ERROR)
self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
# internal async-requests handler.
# data input is json data
def _asyncHandler(self,data):
try:
responses = data['async-responses']
for entry in responses:
if entry['id'] in self.database['async-responses'].keys():
result = self.database['async-responses'].pop(entry['id']) # get the asynch object out of database
# fill in async-result object
if 'error' in entry.keys():
# error happened, handle it
result.error = response_codes('async-responses-handler',entry['status'])
result.error.error = entry['error']
result.is_done = True
if result.callback:
result.callback(result)
else:
return result
else:
# everything is good, fill it out
result.result = b64decode(entry['payload'])
result.raw_data = entry
result.status = entry['status']
result.error = False
for thing in entry.keys():
result.extra[thing]=entry[thing]
result.is_done = True
# call associated callback function
if result.callback:
result.callback(result)
else:
self.log.warn("No callback function given")
else:
# TODO : object not found int asynch database
self.log.warn("No asynch entry for '%s' found in databse",entry['id'])
except:
# TODO error handling here
self.log.error("Bad data encountered and failed to elegantly handle it. ")
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
self.log.error(sys.exc_info())
del tb
return
# default handler for notifications. User should impliment all of these in
# a L2 implimentation or in their webapp.
# @input data is a dictionary
def _defaultHandler(self,data):
if 'async-responses' in data.keys():
self.log.info("async-responses detected : len = %d",len(data["async-responses"]))
self.log.debug(data["async-responses"])
if 'notifications' in data.keys():
self.log.info("notifications' detected : len = %d",len(data["notifications"]))
self.log.debug(data["notifications"])
if 'registrations' in data.keys():
self.log.info("registrations' detected : len = %d",len(data["registrations"]))
self.log.debug(data["registrations"])
if 'reg-updates' in data.keys():
# removed because this happens every 10s or so, spamming the output
self.log.info("reg-updates detected : len = %d",len(data["reg-updates"]))
self.log.debug(data["reg-updates"])
if 'de-registrations' in data.keys():
self.log.info("de-registrations detected : len = %d",len(data["de-registrations"]))
self.log.debug(data["de-registrations"])
if 'registrations-expired' in data.keys():
self.log.info("registrations-expired detected : len = %d",len(data["registrations-expired"]))
self.log.debug(data["registrations-expired"])
# make the requests.
# url is the API url to hit
# query are the optional get params
# versioned tells the API whether to hit the /v#/ version. set to false for
# commands that break with this, like the API and Connector version calls
# TODO: spin this off to be non-blocking
def _getURL(self, url,query={},versioned=True):
if versioned:
return r.get(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
else:
return r.get(self.address+url,headers={"Authorization":"Bearer "+self.bearer},params=query)
# put data to URL with json payload in dataIn
def _putURL(self, url,payload=None,versioned=True):
if self._isJSON(payload):
self.log.debug("PUT payload is json")
if versioned:
return r.put(self.address+self.apiVersion+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,json=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
self.log.debug("PUT payload is NOT json")
if versioned:
return r.put(self.address+self.apiVersion+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.put(self.address+url,data=payload,headers={"Authorization":"Bearer "+self.bearer})
# put data to URL with json payload in dataIn
def _postURL(self, url,payload="",versioned=True):
addr = self.address+self.apiVersion+url if versioned else self.address+url
h = {"Authorization":"Bearer "+self.bearer}
if payload:
self.log.info("POSTing with payload: %s ",payload)
return r.post(addr,data=payload,headers=h)
else:
self.log.info("POSTing")
return r.post(addr,headers=h)
# delete endpoint
def _deleteURL(self, url,versioned=True):
if versioned:
return r.delete(self.address+self.apiVersion+url,headers={"Authorization":"Bearer "+self.bearer})
else:
return r.delete(self.address+url,headers={"Authorization":"Bearer "+self.bearer})
# check if input is json, return true or false accordingly
def _isJSON(self,dataIn):
try:
json.dumps(dataIn)
return True
except:
self.log.debug("[_isJSON] exception triggered, input is not json")
return False
# extend dictionary class so we can instantiate multiple levels at once
class vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# Initialization function, set the token used by this object.
def __init__( self,
token,
webAddress="https://api.connector.mbed.com",
port="80",):
# set token
self.bearer = token
# set version of REST API
self.apiVersion = "/v2"
# Init database, used for callback fn's for various tasks (asynch, subscriptions...etc)
self.database = self.vividict()
self.database['notifications']
self.database['registrations']
self.database['reg-updates']
self.database['de-registrations']
self.database['registrations-expired']
self.database['async-responses']
# longpolling variable
self._stopLongPolling = threading.Event() # must initialize false to avoid race condition
self._stopLongPolling.clear()
#create thread for long polling
self.longPollThread = threading.Thread(target=self.longPoll,name="mdc-api-longpoll")
self.longPollThread.daemon = True # Do this so the thread exits when the overall process does
# set default webAddress and port to mbed connector
self.address = webAddress
self.port = port
# Initialize the callbacks
self.async_responses_callback = self._asyncHandler
self.registrations_expired_callback = self._defaultHandler
self.de_registrations_callback = self._defaultHandler
self.reg_updates_callback = self._defaultHandler
self.registrations_callback = self._defaultHandler
self.notifications_callback = self._defaultHandler
# add logger
self.log = logging.getLogger(name="mdc-api-logger")
self.log.setLevel(logging.ERROR)
self._ch = logging.StreamHandler()
self._ch.setLevel(logging.ERROR)
formatter = logging.Formatter("\r\n[%(levelname)s \t %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
self._ch.setFormatter(formatter)
self.log.addHandler(self._ch)
|
makinacorpus/django-tracking-fields
|
tracking_fields/admin.py
|
TrackingEventAdmin.changelist_view
|
python
|
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
if 'object' in request.GET.keys():
value = request.GET['object'].split(':')
content_type = get_object_or_404(
ContentType,
id=value[0],
)
tracked_object = get_object_or_404(
content_type.model_class(),
id=value[1],
)
extra_context['tracked_object'] = tracked_object
extra_context['tracked_object_opts'] = tracked_object._meta
return super(TrackingEventAdmin, self).changelist_view(
request, extra_context)
|
Get object currently tracked and add a button to get back to it
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/admin.py#L118-L134
| null |
class TrackingEventAdmin(admin.ModelAdmin):
date_hierarchy = 'date'
list_display = ('date', 'action', 'object', 'object_repr')
list_filter = ('action', TrackerEventUserFilter, TrackerEventListFilter,)
search_fields = ('object_repr', 'user_repr',)
readonly_fields = (
'date', 'action', 'object', 'object_repr', 'user', 'user_repr',
)
inlines = (
TrackedFieldModificationAdmin,
)
change_list_template = 'tracking_fields/admin/change_list_event.html'
|
makinacorpus/django-tracking-fields
|
tracking_fields/decorators.py
|
_track_class_related_field
|
python
|
def _track_class_related_field(cls, field):
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
related_name = field_obj.remote_field.get_accessor_name()
if not hasattr(related_cls, '_tracked_related_fields'):
setattr(related_cls, '_tracked_related_fields', {})
if related_field not in related_cls._tracked_related_fields.keys():
related_cls._tracked_related_fields[related_field] = []
# There can be several field from different or same model
# related to a single model.
# Thus _tracked_related_fields will be of the form:
# {
# 'field name on related model': [
# ('field name on current model', 'field name to current model'),
# ('field name on another model', 'field name to another model'),
# ...
# ],
# ...
# }
related_cls._tracked_related_fields[related_field].append(
(field, related_name)
)
_add_signals_to_cls(related_cls)
# Detect m2m fields changes
if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(related_cls, related_field).through,
dispatch_uid=repr(related_cls),
)
|
Track a field on a related model
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L35-L71
| null |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.db.models import ManyToManyField
from django.db.models.signals import (
post_init, post_save, pre_delete, m2m_changed
)
from tracking_fields.tracking import (
tracking_init, tracking_save, tracking_delete, tracking_m2m
)
def _add_signals_to_cls(cls):
# Use repr(cls) to be sure to bound the callback
# only once for each class
post_init.connect(
tracking_init,
sender=cls,
dispatch_uid=repr(cls),
)
post_save.connect(
tracking_save,
sender=cls,
dispatch_uid=repr(cls),
)
pre_delete.connect(
tracking_delete,
sender=cls,
dispatch_uid=repr(cls),
)
def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_field(field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(cls, field).through,
dispatch_uid=repr(cls),
)
def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is_tracked = True
# Do not directly track related fields (tracked on related model)
# or m2m fields (tracked by another signal)
cls._tracked_fields = [
field for field in fields
if '__' not in field
]
def _add_get_tracking_url(cls):
""" Add a method to get the tracking url of an object. """
def get_tracking_url(self):
""" return url to tracking view in admin panel """
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentType.objects.get_for_model(self).pk,
self.pk
)
return '{0}?object={1}'.format(url, object_id)
if not hasattr(cls, 'get_tracking_url'):
setattr(cls, 'get_tracking_url', get_tracking_url)
def track(*fields):
"""
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30)
"""
def inner(cls):
_track_class(cls, fields)
_add_get_tracking_url(cls)
return cls
return inner
|
makinacorpus/django-tracking-fields
|
tracking_fields/decorators.py
|
_track_class_field
|
python
|
def _track_class_field(cls, field):
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_field(field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(cls, field).through,
dispatch_uid=repr(cls),
)
|
Track a field on the current model
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L74-L87
|
[
"def _track_class_related_field(cls, field):\n \"\"\" Track a field on a related model \"\"\"\n # field = field on current model\n # related_field = field on related model\n (field, related_field) = field.split('__', 1)\n field_obj = cls._meta.get_field(field)\n related_cls = field_obj.remote_field.model\n related_name = field_obj.remote_field.get_accessor_name()\n\n if not hasattr(related_cls, '_tracked_related_fields'):\n setattr(related_cls, '_tracked_related_fields', {})\n if related_field not in related_cls._tracked_related_fields.keys():\n related_cls._tracked_related_fields[related_field] = []\n\n # There can be several field from different or same model\n # related to a single model.\n # Thus _tracked_related_fields will be of the form:\n # {\n # 'field name on related model': [\n # ('field name on current model', 'field name to current model'),\n # ('field name on another model', 'field name to another model'),\n # ...\n # ],\n # ...\n # }\n\n related_cls._tracked_related_fields[related_field].append(\n (field, related_name)\n )\n _add_signals_to_cls(related_cls)\n # Detect m2m fields changes\n if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):\n m2m_changed.connect(\n tracking_m2m,\n sender=getattr(related_cls, related_field).through,\n dispatch_uid=repr(related_cls),\n )\n"
] |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.db.models import ManyToManyField
from django.db.models.signals import (
post_init, post_save, pre_delete, m2m_changed
)
from tracking_fields.tracking import (
tracking_init, tracking_save, tracking_delete, tracking_m2m
)
def _add_signals_to_cls(cls):
# Use repr(cls) to be sure to bound the callback
# only once for each class
post_init.connect(
tracking_init,
sender=cls,
dispatch_uid=repr(cls),
)
post_save.connect(
tracking_save,
sender=cls,
dispatch_uid=repr(cls),
)
pre_delete.connect(
tracking_delete,
sender=cls,
dispatch_uid=repr(cls),
)
def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
related_name = field_obj.remote_field.get_accessor_name()
if not hasattr(related_cls, '_tracked_related_fields'):
setattr(related_cls, '_tracked_related_fields', {})
if related_field not in related_cls._tracked_related_fields.keys():
related_cls._tracked_related_fields[related_field] = []
# There can be several field from different or same model
# related to a single model.
# Thus _tracked_related_fields will be of the form:
# {
# 'field name on related model': [
# ('field name on current model', 'field name to current model'),
# ('field name on another model', 'field name to another model'),
# ...
# ],
# ...
# }
related_cls._tracked_related_fields[related_field].append(
(field, related_name)
)
_add_signals_to_cls(related_cls)
# Detect m2m fields changes
if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(related_cls, related_field).through,
dispatch_uid=repr(related_cls),
)
def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is_tracked = True
# Do not directly track related fields (tracked on related model)
# or m2m fields (tracked by another signal)
cls._tracked_fields = [
field for field in fields
if '__' not in field
]
def _add_get_tracking_url(cls):
""" Add a method to get the tracking url of an object. """
def get_tracking_url(self):
""" return url to tracking view in admin panel """
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentType.objects.get_for_model(self).pk,
self.pk
)
return '{0}?object={1}'.format(url, object_id)
if not hasattr(cls, 'get_tracking_url'):
setattr(cls, 'get_tracking_url', get_tracking_url)
def track(*fields):
"""
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30)
"""
def inner(cls):
_track_class(cls, fields)
_add_get_tracking_url(cls)
return cls
return inner
|
makinacorpus/django-tracking-fields
|
tracking_fields/decorators.py
|
_track_class
|
python
|
def _track_class(cls, fields):
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is_tracked = True
# Do not directly track related fields (tracked on related model)
# or m2m fields (tracked by another signal)
cls._tracked_fields = [
field for field in fields
if '__' not in field
]
|
Track fields on the specified model
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L90-L107
|
[
"def _add_signals_to_cls(cls):\n # Use repr(cls) to be sure to bound the callback\n # only once for each class\n post_init.connect(\n tracking_init,\n sender=cls,\n dispatch_uid=repr(cls),\n )\n post_save.connect(\n tracking_save,\n sender=cls,\n dispatch_uid=repr(cls),\n )\n pre_delete.connect(\n tracking_delete,\n sender=cls,\n dispatch_uid=repr(cls),\n )\n",
"def _track_class_field(cls, field):\n \"\"\" Track a field on the current model \"\"\"\n if '__' in field:\n _track_class_related_field(cls, field)\n return\n # Will raise FieldDoesNotExist if there is an error\n cls._meta.get_field(field)\n # Detect m2m fields changes\n if isinstance(cls._meta.get_field(field), ManyToManyField):\n m2m_changed.connect(\n tracking_m2m,\n sender=getattr(cls, field).through,\n dispatch_uid=repr(cls),\n )\n"
] |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.db.models import ManyToManyField
from django.db.models.signals import (
post_init, post_save, pre_delete, m2m_changed
)
from tracking_fields.tracking import (
tracking_init, tracking_save, tracking_delete, tracking_m2m
)
def _add_signals_to_cls(cls):
# Use repr(cls) to be sure to bound the callback
# only once for each class
post_init.connect(
tracking_init,
sender=cls,
dispatch_uid=repr(cls),
)
post_save.connect(
tracking_save,
sender=cls,
dispatch_uid=repr(cls),
)
pre_delete.connect(
tracking_delete,
sender=cls,
dispatch_uid=repr(cls),
)
def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
related_name = field_obj.remote_field.get_accessor_name()
if not hasattr(related_cls, '_tracked_related_fields'):
setattr(related_cls, '_tracked_related_fields', {})
if related_field not in related_cls._tracked_related_fields.keys():
related_cls._tracked_related_fields[related_field] = []
# There can be several field from different or same model
# related to a single model.
# Thus _tracked_related_fields will be of the form:
# {
# 'field name on related model': [
# ('field name on current model', 'field name to current model'),
# ('field name on another model', 'field name to another model'),
# ...
# ],
# ...
# }
related_cls._tracked_related_fields[related_field].append(
(field, related_name)
)
_add_signals_to_cls(related_cls)
# Detect m2m fields changes
if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(related_cls, related_field).through,
dispatch_uid=repr(related_cls),
)
def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_field(field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(cls, field).through,
dispatch_uid=repr(cls),
)
def _add_get_tracking_url(cls):
""" Add a method to get the tracking url of an object. """
def get_tracking_url(self):
""" return url to tracking view in admin panel """
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentType.objects.get_for_model(self).pk,
self.pk
)
return '{0}?object={1}'.format(url, object_id)
if not hasattr(cls, 'get_tracking_url'):
setattr(cls, 'get_tracking_url', get_tracking_url)
def track(*fields):
"""
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30)
"""
def inner(cls):
_track_class(cls, fields)
_add_get_tracking_url(cls)
return cls
return inner
|
makinacorpus/django-tracking-fields
|
tracking_fields/decorators.py
|
_add_get_tracking_url
|
python
|
def _add_get_tracking_url(cls):
def get_tracking_url(self):
""" return url to tracking view in admin panel """
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentType.objects.get_for_model(self).pk,
self.pk
)
return '{0}?object={1}'.format(url, object_id)
if not hasattr(cls, 'get_tracking_url'):
setattr(cls, 'get_tracking_url', get_tracking_url)
|
Add a method to get the tracking url of an object.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L110-L121
| null |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.db.models import ManyToManyField
from django.db.models.signals import (
post_init, post_save, pre_delete, m2m_changed
)
from tracking_fields.tracking import (
tracking_init, tracking_save, tracking_delete, tracking_m2m
)
def _add_signals_to_cls(cls):
# Use repr(cls) to be sure to bound the callback
# only once for each class
post_init.connect(
tracking_init,
sender=cls,
dispatch_uid=repr(cls),
)
post_save.connect(
tracking_save,
sender=cls,
dispatch_uid=repr(cls),
)
pre_delete.connect(
tracking_delete,
sender=cls,
dispatch_uid=repr(cls),
)
def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
related_name = field_obj.remote_field.get_accessor_name()
if not hasattr(related_cls, '_tracked_related_fields'):
setattr(related_cls, '_tracked_related_fields', {})
if related_field not in related_cls._tracked_related_fields.keys():
related_cls._tracked_related_fields[related_field] = []
# There can be several field from different or same model
# related to a single model.
# Thus _tracked_related_fields will be of the form:
# {
# 'field name on related model': [
# ('field name on current model', 'field name to current model'),
# ('field name on another model', 'field name to another model'),
# ...
# ],
# ...
# }
related_cls._tracked_related_fields[related_field].append(
(field, related_name)
)
_add_signals_to_cls(related_cls)
# Detect m2m fields changes
if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(related_cls, related_field).through,
dispatch_uid=repr(related_cls),
)
def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_field(field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(cls, field).through,
dispatch_uid=repr(cls),
)
def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is_tracked = True
# Do not directly track related fields (tracked on related model)
# or m2m fields (tracked by another signal)
cls._tracked_fields = [
field for field in fields
if '__' not in field
]
def track(*fields):
"""
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30)
"""
def inner(cls):
_track_class(cls, fields)
_add_get_tracking_url(cls)
return cls
return inner
|
makinacorpus/django-tracking-fields
|
tracking_fields/decorators.py
|
track
|
python
|
def track(*fields):
def inner(cls):
_track_class(cls, fields)
_add_get_tracking_url(cls)
return cls
return inner
|
Decorator used to track changes on Model's fields.
:Example:
>>> @track('name')
... class Human(models.Model):
... name = models.CharField(max_length=30)
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L124-L137
| null |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.db.models import ManyToManyField
from django.db.models.signals import (
post_init, post_save, pre_delete, m2m_changed
)
from tracking_fields.tracking import (
tracking_init, tracking_save, tracking_delete, tracking_m2m
)
def _add_signals_to_cls(cls):
# Use repr(cls) to be sure to bound the callback
# only once for each class
post_init.connect(
tracking_init,
sender=cls,
dispatch_uid=repr(cls),
)
post_save.connect(
tracking_save,
sender=cls,
dispatch_uid=repr(cls),
)
pre_delete.connect(
tracking_delete,
sender=cls,
dispatch_uid=repr(cls),
)
def _track_class_related_field(cls, field):
""" Track a field on a related model """
# field = field on current model
# related_field = field on related model
(field, related_field) = field.split('__', 1)
field_obj = cls._meta.get_field(field)
related_cls = field_obj.remote_field.model
related_name = field_obj.remote_field.get_accessor_name()
if not hasattr(related_cls, '_tracked_related_fields'):
setattr(related_cls, '_tracked_related_fields', {})
if related_field not in related_cls._tracked_related_fields.keys():
related_cls._tracked_related_fields[related_field] = []
# There can be several field from different or same model
# related to a single model.
# Thus _tracked_related_fields will be of the form:
# {
# 'field name on related model': [
# ('field name on current model', 'field name to current model'),
# ('field name on another model', 'field name to another model'),
# ...
# ],
# ...
# }
related_cls._tracked_related_fields[related_field].append(
(field, related_name)
)
_add_signals_to_cls(related_cls)
# Detect m2m fields changes
if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(related_cls, related_field).through,
dispatch_uid=repr(related_cls),
)
def _track_class_field(cls, field):
""" Track a field on the current model """
if '__' in field:
_track_class_related_field(cls, field)
return
# Will raise FieldDoesNotExist if there is an error
cls._meta.get_field(field)
# Detect m2m fields changes
if isinstance(cls._meta.get_field(field), ManyToManyField):
m2m_changed.connect(
tracking_m2m,
sender=getattr(cls, field).through,
dispatch_uid=repr(cls),
)
def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is_tracked = True
# Do not directly track related fields (tracked on related model)
# or m2m fields (tracked by another signal)
cls._tracked_fields = [
field for field in fields
if '__' not in field
]
def _add_get_tracking_url(cls):
""" Add a method to get the tracking url of an object. """
def get_tracking_url(self):
""" return url to tracking view in admin panel """
url = reverse('admin:tracking_fields_trackingevent_changelist')
object_id = '{0}%3A{1}'.format(
ContentType.objects.get_for_model(self).pk,
self.pk
)
return '{0}?object={1}'.format(url, object_id)
if not hasattr(cls, 'get_tracking_url'):
setattr(cls, 'get_tracking_url', get_tracking_url)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_set_original_fields
|
python
|
def _set_original_fields(instance):
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
|
Save fields value, only for non-m2m fields.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L29-L54
|
[
"def _set_original_field(instance, field):\n if instance.pk is None:\n original_fields[field] = None\n else:\n if isinstance(instance._meta.get_field(field), ForeignKey):\n # Only get the PK, we don't want to get the object\n # (which would make an additional request)\n original_fields[field] = getattr(instance,\n '{0}_id'.format(field))\n else:\n original_fields[field] = getattr(instance, field)\n"
] |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_has_changed
|
python
|
def _has_changed(instance):
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
|
Check if some tracked fields have changed
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L57-L75
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_has_changed_related
|
python
|
def _has_changed_related(instance):
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
|
Check if some related tracked fields have changed
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L78-L97
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_create_event
|
python
|
def _create_event(instance, action):
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
|
Create a new event, getting the use if django-cuser is available.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L100-L117
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_create_tracked_field
|
python
|
def _create_tracked_field(event, instance, field, fieldname=None):
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
|
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L145-L170
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_create_create_tracking_event
|
python
|
def _create_create_tracking_event(instance):
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
|
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L173-L180
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_create_update_tracking_event
|
python
|
def _create_update_tracking_event(instance):
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
|
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L183-L200
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_create_update_tracking_related_event
|
python
|
def _create_update_tracking_related_event(instance):
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
|
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L203-L239
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_get_m2m_field
|
python
|
def _get_m2m_field(model, sender):
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
|
Get the field name from a model and a sender from m2m_changed signal.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L249-L260
| null |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
_create_tracked_event_m2m
|
python
|
def _create_tracked_event_m2m(model, instance, sender, objects, action):
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
|
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L283-L320
|
[
"def _create_event(instance, action):\n \"\"\"\n Create a new event, getting the use if django-cuser is available.\n \"\"\"\n user = None\n user_repr = repr(user)\n if CUSER:\n user = CuserMiddleware.get_user()\n user_repr = repr(user)\n if user is not None and user.is_anonymous:\n user = None\n return TrackingEvent.objects.create(\n action=action,\n object=instance,\n object_repr=repr(instance),\n user=user,\n user_repr=user_repr,\n )\n",
"def _get_m2m_field(model, sender):\n \"\"\"\n Get the field name from a model and a sender from m2m_changed signal.\n \"\"\"\n for field in getattr(model, '_tracked_fields', []):\n if isinstance(model._meta.get_field(field), ManyToManyField):\n if getattr(model, field).through == sender:\n return field\n for field in getattr(model, '_tracked_related_fields', {}).keys():\n if isinstance(model._meta.get_field(field), ManyToManyField):\n if getattr(model, field).through == sender:\n return field\n",
"def _create_tracked_field_m2m(event, instance, field, objects, action,\n fieldname=None):\n fieldname = fieldname or field\n before = list(getattr(instance, field).all())\n if action == 'ADD':\n after = before + objects\n elif action == 'REMOVE':\n after = [obj for obj in before if obj not in objects]\n elif action == 'CLEAR':\n after = []\n before = list(map(six.text_type, before))\n after = list(map(six.text_type, after))\n return TrackedFieldModification.objects.create(\n event=event,\n field=fieldname,\n old_value=json.dumps(before),\n new_value=json.dumps(after)\n )\n"
] |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
tracking_save
|
python
|
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
|
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L332-L349
|
[
"def _has_changed(instance):\n \"\"\"\n Check if some tracked fields have changed\n \"\"\"\n for field, value in instance._original_fields.items():\n if field != 'pk' and \\\n not isinstance(instance._meta.get_field(field), ManyToManyField):\n try:\n if field in getattr(instance, '_tracked_fields', []):\n if isinstance(instance._meta.get_field(field), ForeignKey):\n if getattr(instance, '{0}_id'.format(field)) != value:\n return True\n else:\n if getattr(instance, field) != value:\n return True\n except TypeError:\n # Can't compare old and new value, should be different.\n return True\n return False\n",
"def _has_changed_related(instance):\n \"\"\"\n Check if some related tracked fields have changed\n \"\"\"\n tracked_related_fields = getattr(\n instance,\n '_tracked_related_fields',\n {}\n ).keys()\n for field, value in instance._original_fields.items():\n if field != 'pk' and \\\n not isinstance(instance._meta.get_field(field), ManyToManyField):\n if field in tracked_related_fields:\n if isinstance(instance._meta.get_field(field), ForeignKey):\n if getattr(instance, '{0}_id'.format(field)) != value:\n return True\n else:\n if getattr(instance, field) != value:\n return True\n return False\n"
] |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
"""
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
"""
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
makinacorpus/django-tracking-fields
|
tracking_fields/tracking.py
|
tracking_m2m
|
python
|
def tracking_m2m(
sender, instance, action, reverse, model, pk_set, using, **kwargs
):
action_event = {
'pre_clear': 'CLEAR',
'pre_add': 'ADD',
'pre_remove': 'REMOVE',
}
if (action not in action_event.keys()):
return
if reverse:
if action == 'pre_clear':
# It will actually be a remove of ``instance`` on every
# tracked object being related
action = 'pre_remove'
# pk_set is None for clear events, we need to get objects' pk.
field = _get_m2m_field(model, sender)
field = model._meta.get_field(field).remote_field.get_accessor_name()
pk_set = set([obj.id for obj in getattr(instance, field).all()])
# Create an event for each object being tracked
for pk in pk_set:
tracked_instance = model.objects.get(pk=pk)
objects = [instance]
_create_tracked_event_m2m(
model, tracked_instance, sender, objects, action_event[action]
)
else:
# Get the model of the object being tracked
tracked_model = instance._meta.model
objects = []
if pk_set is not None:
objects = [model.objects.get(pk=pk) for pk in pk_set]
_create_tracked_event_m2m(
tracked_model, instance, sender, objects, action_event[action]
)
|
m2m_changed callback.
The idea is to get the model and the instance of the object being tracked,
and the different objects being added/removed. It is then send to the
``_create_tracked_field_m2m`` method to extract the proper attribute for
the TrackedFieldModification.
|
train
|
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L359-L400
|
[
"def _get_m2m_field(model, sender):\n \"\"\"\n Get the field name from a model and a sender from m2m_changed signal.\n \"\"\"\n for field in getattr(model, '_tracked_fields', []):\n if isinstance(model._meta.get_field(field), ManyToManyField):\n if getattr(model, field).through == sender:\n return field\n for field in getattr(model, '_tracked_related_fields', {}).keys():\n if isinstance(model._meta.get_field(field), ManyToManyField):\n if getattr(model, field).through == sender:\n return field\n",
"def _create_tracked_event_m2m(model, instance, sender, objects, action):\n \"\"\"\n Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``\n for a m2m modification.\n The first thing needed is to get the m2m field on the object being tracked.\n The current related objects are then taken (``old_value``).\n The new value is calculated in function of ``action`` (``new_value``).\n The ``TrackedFieldModification`` is created with the proper parameters.\n\n :param model: The model of the object being tracked.\n :param instance: The instance of the object being tracked.\n :param sender: The m2m through relationship instance.\n :param objects: The list of objects being added/removed.\n :param action: The action from the m2m_changed signal.\n \"\"\"\n field = _get_m2m_field(model, sender)\n if field in getattr(model, '_tracked_related_fields', {}).keys():\n # In case of a m2m tracked on a related model\n related_fields = model._tracked_related_fields[field]\n for related_field in related_fields:\n try:\n related_instances = getattr(instance, related_field[1])\n except ObjectDoesNotExist:\n continue\n # FIXME: isinstance(related_instances, RelatedManager ?)\n if hasattr(related_instances, 'all'):\n related_instances = related_instances.all()\n else:\n related_instances = [related_instances]\n for related_instance in related_instances:\n event = _create_event(related_instance, action)\n fieldname = '{0}__{1}'.format(related_field[0], field)\n _create_tracked_field_m2m(\n event, instance, field, objects, action, fieldname\n )\n if field in getattr(model, '_tracked_fields', []):\n event = _create_event(instance, action)\n _create_tracked_field_m2m(event, instance, field, objects, action)\n"
] |
from __future__ import unicode_literals
import datetime
import json
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, ManyToManyField
from django.db.models.fields.files import FieldFile
from django.db.models.fields.related import ForeignKey
from django.utils import six
try:
from cuser.middleware import CuserMiddleware
CUSER = True
except ImportError:
CUSER = False
from tracking_fields.models import (
TrackingEvent, TrackedFieldModification,
CREATE, UPDATE, DELETE
)
logger = logging.getLogger(__name__)
# ======================= HELPERS ====================
def _set_original_fields(instance):
"""
Save fields value, only for non-m2m fields.
"""
original_fields = {}
def _set_original_field(instance, field):
if instance.pk is None:
original_fields[field] = None
else:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Only get the PK, we don't want to get the object
# (which would make an additional request)
original_fields[field] = getattr(instance,
'{0}_id'.format(field))
else:
original_fields[field] = getattr(instance, field)
for field in getattr(instance, '_tracked_fields', []):
_set_original_field(instance, field)
for field in getattr(instance, '_tracked_related_fields', {}).keys():
_set_original_field(instance, field)
instance._original_fields = original_fields
# Include pk to detect the creation of an object
instance._original_fields['pk'] = instance.pk
def _has_changed(instance):
"""
Check if some tracked fields have changed
"""
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if field in getattr(instance, '_tracked_fields', []):
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
except TypeError:
# Can't compare old and new value, should be different.
return True
return False
def _has_changed_related(instance):
"""
Check if some related tracked fields have changed
"""
tracked_related_fields = getattr(
instance,
'_tracked_related_fields',
{}
).keys()
for field, value in instance._original_fields.items():
if field != 'pk' and \
not isinstance(instance._meta.get_field(field), ManyToManyField):
if field in tracked_related_fields:
if isinstance(instance._meta.get_field(field), ForeignKey):
if getattr(instance, '{0}_id'.format(field)) != value:
return True
else:
if getattr(instance, field) != value:
return True
return False
def _create_event(instance, action):
"""
Create a new event, getting the use if django-cuser is available.
"""
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object=instance,
object_repr=repr(instance),
user=user,
user_repr=user_repr,
)
def _serialize_field(field):
if isinstance(field, datetime.datetime):
return json.dumps(
field.strftime('%Y-%m-%d %H:%M:%S'), ensure_ascii=False
)
if isinstance(field, datetime.date):
return json.dumps(
field.strftime('%Y-%m-%d'), ensure_ascii=False
)
if isinstance(field, FieldFile):
try:
return json.dumps(field.path, ensure_ascii=False)
except ValueError:
# No file
return json.dumps(None, ensure_ascii=False)
if isinstance(field, Model):
return json.dumps(six.text_type(field),
ensure_ascii=False)
try:
return json.dumps(field, ensure_ascii=False)
except TypeError:
logger.warning("Could not serialize field {0}".format(repr(field)))
return json.dumps(repr(field), ensure_ascii=False)
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: The displayed name for the field. Default to field.
"""
fieldname = fieldname or field
if isinstance(instance._meta.get_field(field), ForeignKey):
# We only have the pk, we need to get the actual object
model = instance._meta.get_field(field).remote_field.model
pk = instance._original_fields[field]
try:
old_value = model.objects.get(pk=pk)
except model.DoesNotExist:
old_value = None
else:
old_value = instance._original_fields[field]
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=_serialize_field(old_value),
new_value=_serialize_field(getattr(instance, field))
)
def _create_create_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
"""
event = _create_event(instance, CREATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
_create_tracked_field(event, instance, field)
def _create_update_tracking_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
"""
event = _create_event(instance, UPDATE)
for field in instance._tracked_fields:
if not isinstance(instance._meta.get_field(field), ManyToManyField):
try:
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
_create_tracked_field(event, instance, field)
except TypeError:
# Can't compare old and new value, should be different.
_create_tracked_field(event, instance, field)
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
# Compare pk
value = getattr(instance, '{0}_id'.format(field))
else:
value = getattr(instance, field)
if instance._original_fields[field] != value:
for related_field in related_fields:
events.setdefault(related_field, []).append(field)
# Create the events from the events dict
for related_field, fields in events.items():
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, UPDATE)
for field in fields:
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field(
event, instance, field, fieldname=fieldname
)
def _create_delete_tracking_event(instance):
"""
Create a TrackingEvent for a DELETE event.
"""
_create_event(instance, DELETE)
def _get_m2m_field(model, sender):
"""
Get the field name from a model and a sender from m2m_changed signal.
"""
for field in getattr(model, '_tracked_fields', []):
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
for field in getattr(model, '_tracked_related_fields', {}).keys():
if isinstance(model._meta.get_field(field), ManyToManyField):
if getattr(model, field).through == sender:
return field
def _create_tracked_field_m2m(event, instance, field, objects, action,
fieldname=None):
fieldname = fieldname or field
before = list(getattr(instance, field).all())
if action == 'ADD':
after = before + objects
elif action == 'REMOVE':
after = [obj for obj in before if obj not in objects]
elif action == 'CLEAR':
after = []
before = list(map(six.text_type, before))
after = list(map(six.text_type, after))
return TrackedFieldModification.objects.create(
event=event,
field=fieldname,
old_value=json.dumps(before),
new_value=json.dumps(after)
)
def _create_tracked_event_m2m(model, instance, sender, objects, action):
"""
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification``
for a m2m modification.
The first thing needed is to get the m2m field on the object being tracked.
The current related objects are then taken (``old_value``).
The new value is calculated in function of ``action`` (``new_value``).
The ``TrackedFieldModification`` is created with the proper parameters.
:param model: The model of the object being tracked.
:param instance: The instance of the object being tracked.
:param sender: The m2m through relationship instance.
:param objects: The list of objects being added/removed.
:param action: The action from the m2m_changed signal.
"""
field = _get_m2m_field(model, sender)
if field in getattr(model, '_tracked_related_fields', {}).keys():
# In case of a m2m tracked on a related model
related_fields = model._tracked_related_fields[field]
for related_field in related_fields:
try:
related_instances = getattr(instance, related_field[1])
except ObjectDoesNotExist:
continue
# FIXME: isinstance(related_instances, RelatedManager ?)
if hasattr(related_instances, 'all'):
related_instances = related_instances.all()
else:
related_instances = [related_instances]
for related_instance in related_instances:
event = _create_event(related_instance, action)
fieldname = '{0}__{1}'.format(related_field[0], field)
_create_tracked_field_m2m(
event, instance, field, objects, action, fieldname
)
if field in getattr(model, '_tracked_fields', []):
event = _create_event(instance, action)
_create_tracked_field_m2m(event, instance, field, objects, action)
# ======================= CALLBACKS ====================
def tracking_init(sender, instance, **kwargs):
"""
Post init, save the current state of the object to compare it before a save
"""
_set_original_fields(instance)
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_create_create_tracking_event(instance)
else:
# Update
_create_update_tracking_event(instance)
if _has_changed_related(instance):
# Because an object need to be saved before being related,
# it can only be an update
_create_update_tracking_related_event(instance)
if _has_changed(instance) or _has_changed_related(instance):
_set_original_fields(instance)
def tracking_delete(sender, instance, using, **kwargs):
"""
Post delete callback
"""
_create_delete_tracking_event(instance)
|
Grk0/python-libconf
|
libconf.py
|
decode_escapes
|
python
|
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
|
Unescape libconfig string literals
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L50-L55
| null |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
load
|
python
|
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
|
Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L476-L498
|
[
"def from_file(cls, f, filename=None, includedir='', seenfiles=None):\n '''Create a token stream by reading an input file\n\n Read tokens from `f`. If an include directive ('@include \"file.cfg\"')\n is found, read its contents as well.\n\n The `filename` argument is used for error messages and to detect\n circular imports. ``includedir`` sets the lookup directory for included\n files. ``seenfiles`` is used internally to detect circular includes,\n and should normally not be supplied by users of is function.\n '''\n\n if filename is None:\n filename = getattr(f, 'name', '<unknown>')\n if seenfiles is None:\n seenfiles = set()\n\n if filename in seenfiles:\n raise ConfigParseError(\"Circular include: %r\" % (filename,))\n seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.\n\n tokenizer = Tokenizer(filename=filename)\n lines = []\n tokens = []\n for line in f:\n m = re.match(r'@include \"(.*)\"$', line.strip())\n if m:\n tokens.extend(tokenizer.tokenize(''.join(lines)))\n lines = [re.sub(r'\\S', ' ', line)]\n\n includefilename = decode_escapes(m.group(1))\n includefilename = os.path.join(includedir, includefilename)\n try:\n includefile = open(includefilename, \"r\")\n except IOError:\n raise ConfigParseError(\"Could not open include file %r\" %\n (includefilename,))\n\n with includefile:\n includestream = cls.from_file(includefile,\n filename=includefilename,\n includedir=includedir,\n seenfiles=seenfiles)\n tokens.extend(includestream.tokens)\n\n else:\n lines.append(line)\n\n tokens.extend(tokenizer.tokenize(''.join(lines)))\n return cls(tokens)\n",
"def parse(self):\n return self.configuration()\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
loads
|
python
|
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
|
Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L501-L521
|
[
"def load(f, filename=None, includedir=''):\n '''Load the contents of ``f`` (a file-like object) to a Python object\n\n The returned object is a subclass of ``dict`` that exposes string keys as\n attributes as well.\n\n Example:\n\n >>> with open('test/example.cfg') as f:\n ... config = libconf.load(f)\n >>> config['window']['title']\n 'libconfig example'\n >>> config.window.title\n 'libconfig example'\n '''\n\n if isinstance(f.read(0), bytes):\n raise TypeError(\"libconf.load() input file must by unicode\")\n\n tokenstream = TokenStream.from_file(f,\n filename=filename,\n includedir=includedir)\n return Parser(tokenstream).parse()\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
dump_string
|
python
|
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
|
Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L555-L572
| null |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
get_dump_type
|
python
|
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
|
Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L575-L606
|
[
"def isint(i):\n return isinstance(i, (int, long))\n",
"def isint(i):\n return isinstance(i, int)\n",
"def is_long_int(i):\n '''Return True if argument should be dumped as int64 type\n\n Either because the argument is an instance of LibconfInt64, or\n because it exceeds the 32bit integer value range.\n '''\n\n return (isinstance(i, LibconfInt64) or\n not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
get_array_value_dtype
|
python
|
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
|
Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L609-L646
|
[
"def get_dump_type(value):\n '''Get the libconfig datatype of a value\n\n Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),\n ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),\n ``'f'`` (float), or ``'s'`` (string).\n\n Produces the proper type for LibconfList, LibconfArray, LibconfInt64\n instances.\n '''\n\n if isinstance(value, dict):\n return 'd'\n if isinstance(value, tuple):\n return 'l'\n if isinstance(value, list):\n return 'a'\n\n # Test bool before int since isinstance(True, int) == True.\n if isinstance(value, bool):\n return 'b'\n if isint(value):\n if is_long_int(value):\n return 'i64'\n else:\n return 'i'\n if isinstance(value, float):\n return 'f'\n if isstr(value):\n return 's'\n\n return None\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
dump_value
|
python
|
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
|
Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L649-L692
|
[
"def dump_int(i):\n '''Stringize ``i``, append 'L' suffix if necessary'''\n return str(i) + ('L' if is_long_int(i) else '')\n",
"def dump_string(s):\n '''Stringize ``s``, adding double quotes and escaping as necessary\n\n Backslash escape backslashes, double quotes, ``\\f``, ``\\n``, ``\\r``, and\n ``\\t``. Escape all remaining unprintable characters in ``\\xFF``-style.\n The returned string will be surrounded by double quotes.\n '''\n\n s = (s.replace('\\\\', '\\\\\\\\')\n .replace('\"', '\\\\\"')\n .replace('\\f', r'\\f')\n .replace('\\n', r'\\n')\n .replace('\\r', r'\\r')\n .replace('\\t', r'\\t'))\n s = UNPRINTABLE_CHARACTER_RE.sub(\n lambda m: r'\\x{:02x}'.format(ord(m.group(0))),\n s)\n return '\"' + s + '\"'\n",
"def get_dump_type(value):\n '''Get the libconfig datatype of a value\n\n Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),\n ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),\n ``'f'`` (float), or ``'s'`` (string).\n\n Produces the proper type for LibconfList, LibconfArray, LibconfInt64\n instances.\n '''\n\n if isinstance(value, dict):\n return 'd'\n if isinstance(value, tuple):\n return 'l'\n if isinstance(value, list):\n return 'a'\n\n # Test bool before int since isinstance(True, int) == True.\n if isinstance(value, bool):\n return 'b'\n if isint(value):\n if is_long_int(value):\n return 'i64'\n else:\n return 'i'\n if isinstance(value, float):\n return 'f'\n if isstr(value):\n return 's'\n\n return None\n",
"def get_array_value_dtype(lst):\n '''Return array value type, raise ConfigSerializeError for invalid arrays\n\n Libconfig arrays must only contain scalar values and all elements must be\n of the same libconfig data type. Raises ConfigSerializeError if these\n invariants are not met.\n\n Returns the value type of the array. If an array contains both int and\n long int data types, the return datatype will be ``'i64'``.\n '''\n\n array_value_type = None\n for value in lst:\n dtype = get_dump_type(value)\n if dtype not in {'b', 'i', 'i64', 'f', 's'}:\n raise ConfigSerializeError(\n \"Invalid datatype in array (may only contain scalars):\"\n \"%r of type %s\" % (value, type(value)))\n\n if array_value_type is None:\n array_value_type = dtype\n continue\n\n if array_value_type == dtype:\n continue\n\n if array_value_type == 'i' and dtype == 'i64':\n array_value_type = 'i64'\n continue\n\n if array_value_type == 'i64' and dtype == 'i':\n continue\n\n raise ConfigSerializeError(\n \"Mixed types in array (all elements must have same type):\"\n \"%r of type %s\" % (value, type(value)))\n\n return array_value_type\n",
"def dump_dict(cfg, f, indent=0):\n '''Save a dictionary of attributes'''\n\n for key in cfg:\n if not isstr(key):\n raise ConfigSerializeError(\"Dict keys must be strings: %r\" %\n (key,))\n dump_value(key, cfg[key], f, indent)\n f.write(u';\\n')\n",
"def dump_collection(cfg, f, indent=0):\n '''Save a collection of attributes'''\n\n for i, value in enumerate(cfg):\n dump_value(None, value, f, indent)\n if i < len(cfg) - 1:\n f.write(u',\\n')\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
dump_collection
|
python
|
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
|
Save a collection of attributes
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L695-L701
|
[
"def dump_value(key, value, f, indent=0):\n '''Save a value of any libconfig type\n\n This function serializes takes ``key`` and ``value`` and serializes them\n into ``f``. If ``key`` is ``None``, a list-style output is produced.\n Otherwise, output has ``key = value`` format.\n '''\n\n spaces = ' ' * indent\n\n if key is None:\n key_prefix = ''\n key_prefix_nl = ''\n else:\n key_prefix = key + ' = '\n key_prefix_nl = key + ' =\\n' + spaces\n\n dtype = get_dump_type(value)\n if dtype == 'd':\n f.write(u'{}{}{{\\n'.format(spaces, key_prefix_nl))\n dump_dict(value, f, indent + 4)\n f.write(u'{}}}'.format(spaces))\n elif dtype == 'l':\n f.write(u'{}{}(\\n'.format(spaces, key_prefix_nl))\n dump_collection(value, f, indent + 4)\n f.write(u'\\n{})'.format(spaces))\n elif dtype == 'a':\n f.write(u'{}{}[\\n'.format(spaces, key_prefix_nl))\n value_dtype = get_array_value_dtype(value)\n\n # If int array contains one or more Int64, promote all values to i64.\n if value_dtype == 'i64':\n value = [LibconfInt64(v) for v in value]\n dump_collection(value, f, indent + 4)\n f.write(u'\\n{}]'.format(spaces))\n elif dtype == 's':\n f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))\n elif dtype == 'i' or dtype == 'i64':\n f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))\n elif dtype == 'f' or dtype == 'b':\n f.write(u'{}{}{}'.format(spaces, key_prefix, value))\n else:\n raise ConfigSerializeError(\"Can not serialize object %r of type %s\" %\n (value, type(value)))\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
dump_dict
|
python
|
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
|
Save a dictionary of attributes
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L704-L712
|
[
"def isstr(s):\n return isinstance(s, basestring)\n",
"def isstr(s):\n return isinstance(s, str)\n",
"def dump_value(key, value, f, indent=0):\n '''Save a value of any libconfig type\n\n This function serializes takes ``key`` and ``value`` and serializes them\n into ``f``. If ``key`` is ``None``, a list-style output is produced.\n Otherwise, output has ``key = value`` format.\n '''\n\n spaces = ' ' * indent\n\n if key is None:\n key_prefix = ''\n key_prefix_nl = ''\n else:\n key_prefix = key + ' = '\n key_prefix_nl = key + ' =\\n' + spaces\n\n dtype = get_dump_type(value)\n if dtype == 'd':\n f.write(u'{}{}{{\\n'.format(spaces, key_prefix_nl))\n dump_dict(value, f, indent + 4)\n f.write(u'{}}}'.format(spaces))\n elif dtype == 'l':\n f.write(u'{}{}(\\n'.format(spaces, key_prefix_nl))\n dump_collection(value, f, indent + 4)\n f.write(u'\\n{})'.format(spaces))\n elif dtype == 'a':\n f.write(u'{}{}[\\n'.format(spaces, key_prefix_nl))\n value_dtype = get_array_value_dtype(value)\n\n # If int array contains one or more Int64, promote all values to i64.\n if value_dtype == 'i64':\n value = [LibconfInt64(v) for v in value]\n dump_collection(value, f, indent + 4)\n f.write(u'\\n{}]'.format(spaces))\n elif dtype == 's':\n f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))\n elif dtype == 'i' or dtype == 'i64':\n f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))\n elif dtype == 'f' or dtype == 'b':\n f.write(u'{}{}{}'.format(spaces, key_prefix, value))\n else:\n raise ConfigSerializeError(\"Can not serialize object %r of type %s\" %\n (value, type(value)))\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
dumps
|
python
|
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
|
Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L715-L726
|
[
"def dump(cfg, f):\n '''Serialize ``cfg`` as a libconfig-formatted stream into ``f``\n\n ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values\n (numbers, strings, booleans, possibly nested dicts, lists, and tuples).\n\n ``f`` must be a ``file``-like object with a ``write()`` method.\n '''\n\n if not isinstance(cfg, dict):\n raise ConfigSerializeError(\n 'dump() requires a dict as input, not %r of type %r' %\n (cfg, type(cfg)))\n\n dump_dict(cfg, f, 0)\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
dump
|
python
|
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
|
Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L729-L743
|
[
"def dump_dict(cfg, f, indent=0):\n '''Save a dictionary of attributes'''\n\n for key in cfg:\n if not isstr(key):\n raise ConfigSerializeError(\"Dict keys must be strings: %r\" %\n (key,))\n dump_value(key, cfg[key], f, indent)\n f.write(u';\\n')\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
# main(): small example of how to use libconf
#############################################
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
main
|
python
|
def main():
'''Open the libconfig file specified by sys.argv[1] and pretty-print it'''
global output
if len(sys.argv[1:]) == 1:
with io.open(sys.argv[1], 'r', encoding='utf-8') as f:
output = load(f)
else:
output = load(sys.stdin)
dump(output, sys.stdout)
|
Open the libconfig file specified by sys.argv[1] and pretty-print it
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L749-L758
|
[
"def dump(cfg, f):\n '''Serialize ``cfg`` as a libconfig-formatted stream into ``f``\n\n ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values\n (numbers, strings, booleans, possibly nested dicts, lists, and tuples).\n\n ``f`` must be a ``file``-like object with a ``write()`` method.\n '''\n\n if not isinstance(cfg, dict):\n raise ConfigSerializeError(\n 'dump() requires a dict as input, not %r of type %r' %\n (cfg, type(cfg)))\n\n dump_dict(cfg, f, 0)\n",
"def load(f, filename=None, includedir=''):\n '''Load the contents of ``f`` (a file-like object) to a Python object\n\n The returned object is a subclass of ``dict`` that exposes string keys as\n attributes as well.\n\n Example:\n\n >>> with open('test/example.cfg') as f:\n ... config = libconf.load(f)\n >>> config['window']['title']\n 'libconfig example'\n >>> config.window.title\n 'libconfig example'\n '''\n\n if isinstance(f.read(0), bytes):\n raise TypeError(\"libconf.load() input file must by unicode\")\n\n tokenstream = TokenStream.from_file(f,\n filename=filename,\n includedir=includedir)\n return Parser(tokenstream).parse()\n"
] |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
LONGTYPE = long
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
LONGTYPE = int
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return self.__getitem__(attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
if self.is_long:
self.value = LibconfInt64(self.value)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("libconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
class LibconfList(tuple):
pass
class LibconfArray(list):
pass
class LibconfInt64(LONGTYPE):
pass
def is_long_int(i):
'''Return True if argument should be dumped as int64 type
Either because the argument is an instance of LibconfInt64, or
because it exceeds the 32bit integer value range.
'''
return (isinstance(i, LibconfInt64) or
not (SMALL_INT_MIN <= i <= SMALL_INT_MAX))
def dump_int(i):
'''Stringize ``i``, append 'L' suffix if necessary'''
return str(i) + ('L' if is_long_int(i) else '')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def get_dump_type(value):
'''Get the libconfig datatype of a value
Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),
``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),
``'f'`` (float), or ``'s'`` (string).
Produces the proper type for LibconfList, LibconfArray, LibconfInt64
instances.
'''
if isinstance(value, dict):
return 'd'
if isinstance(value, tuple):
return 'l'
if isinstance(value, list):
return 'a'
# Test bool before int since isinstance(True, int) == True.
if isinstance(value, bool):
return 'b'
if isint(value):
if is_long_int(value):
return 'i64'
else:
return 'i'
if isinstance(value, float):
return 'f'
if isstr(value):
return 's'
return None
def get_array_value_dtype(lst):
'''Return array value type, raise ConfigSerializeError for invalid arrays
Libconfig arrays must only contain scalar values and all elements must be
of the same libconfig data type. Raises ConfigSerializeError if these
invariants are not met.
Returns the value type of the array. If an array contains both int and
long int data types, the return datatype will be ``'i64'``.
'''
array_value_type = None
for value in lst:
dtype = get_dump_type(value)
if dtype not in {'b', 'i', 'i64', 'f', 's'}:
raise ConfigSerializeError(
"Invalid datatype in array (may only contain scalars):"
"%r of type %s" % (value, type(value)))
if array_value_type is None:
array_value_type = dtype
continue
if array_value_type == dtype:
continue
if array_value_type == 'i' and dtype == 'i64':
array_value_type = 'i64'
continue
if array_value_type == 'i64' and dtype == 'i':
continue
raise ConfigSerializeError(
"Mixed types in array (all elements must have same type):"
"%r of type %s" % (value, type(value)))
return array_value_type
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' =\n' + spaces
dtype = get_dump_type(value)
if dtype == 'd':
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif dtype == 'l':
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif dtype == 'a':
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
value_dtype = get_array_value_dtype(value)
# If int array contains one or more Int64, promote all values to i64.
if value_dtype == 'i64':
value = [LibconfInt64(v) for v in value]
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif dtype == 's':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif dtype == 'i' or dtype == 'i64':
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif dtype == 'f' or dtype == 'b':
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u';\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
# main(): small example of how to use libconf
#############################################
if __name__ == '__main__':
main()
|
Grk0/python-libconf
|
libconf.py
|
Tokenizer.tokenize
|
python
|
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
|
Yield tokens from the input string or throw ConfigParseError
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L178-L206
| null |
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
|
Grk0/python-libconf
|
libconf.py
|
TokenStream.from_file
|
python
|
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
|
Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L224-L273
|
[
"def decode_escapes(s):\n '''Unescape libconfig string literals'''\n def decode_match(match):\n return codecs.decode(match.group(0), 'unicode-escape')\n\n return ESCAPE_SEQUENCE_RE.sub(decode_match, s)\n",
"def tokenize(self, string):\n '''Yield tokens from the input string or throw ConfigParseError'''\n pos = 0\n while pos < len(string):\n m = SKIP_RE.match(string, pos=pos)\n if m:\n skip_lines = m.group(0).split('\\n')\n if len(skip_lines) > 1:\n self.row += len(skip_lines) - 1\n self.column = 1 + len(skip_lines[-1])\n else:\n self.column += len(skip_lines[0])\n\n pos = m.end()\n continue\n\n for cls, type, regex in self.token_map:\n m = regex.match(string, pos=pos)\n if m:\n yield cls(type, m.group(0),\n self.filename, self.row, self.column)\n self.column += len(m.group(0))\n pos = m.end()\n break\n",
"def from_file(cls, f, filename=None, includedir='', seenfiles=None):\n '''Create a token stream by reading an input file\n\n Read tokens from `f`. If an include directive ('@include \"file.cfg\"')\n is found, read its contents as well.\n\n The `filename` argument is used for error messages and to detect\n circular imports. ``includedir`` sets the lookup directory for included\n files. ``seenfiles`` is used internally to detect circular includes,\n and should normally not be supplied by users of is function.\n '''\n\n if filename is None:\n filename = getattr(f, 'name', '<unknown>')\n if seenfiles is None:\n seenfiles = set()\n\n if filename in seenfiles:\n raise ConfigParseError(\"Circular include: %r\" % (filename,))\n seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.\n\n tokenizer = Tokenizer(filename=filename)\n lines = []\n tokens = []\n for line in f:\n m = re.match(r'@include \"(.*)\"$', line.strip())\n if m:\n tokens.extend(tokenizer.tokenize(''.join(lines)))\n lines = [re.sub(r'\\S', ' ', line)]\n\n includefilename = decode_escapes(m.group(1))\n includefilename = os.path.join(includedir, includefilename)\n try:\n includefile = open(includefilename, \"r\")\n except IOError:\n raise ConfigParseError(\"Could not open include file %r\" %\n (includefilename,))\n\n with includefile:\n includestream = cls.from_file(includefile,\n filename=includefilename,\n includedir=includedir,\n seenfiles=seenfiles)\n tokens.extend(includestream.tokens)\n\n else:\n lines.append(line)\n\n tokens.extend(tokenizer.tokenize(''.join(lines)))\n return cls(tokens)\n"
] |
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
|
Grk0/python-libconf
|
libconf.py
|
TokenStream.peek
|
python
|
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
|
Return (but do not consume) the next token
At the end of input, ``None`` is returned.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L275-L284
| null |
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
|
Grk0/python-libconf
|
libconf.py
|
TokenStream.accept
|
python
|
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
|
Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L286-L304
|
[
"def peek(self):\n '''Return (but do not consume) the next token\n\n At the end of input, ``None`` is returned.\n '''\n\n if self.position >= len(self.tokens):\n return None\n\n return self.tokens[self.position]\n"
] |
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
|
Grk0/python-libconf
|
libconf.py
|
TokenStream.expect
|
python
|
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
|
Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L306-L319
|
[
"def accept(self, *args):\n '''Consume and return the next token if it has the correct type\n\n Multiple token types (as strings, e.g. 'integer64') can be given\n as arguments. If the next token is one of them, consume and return it.\n\n If the token type doesn't match, return None.\n '''\n\n token = self.peek()\n if token is None:\n return None\n\n for arg in args:\n if token.type == arg:\n self.position += 1\n return token\n\n return None\n",
"def error(self, msg):\n '''Raise a ConfigParseError at the current input position'''\n if self.finished():\n raise ConfigParseError(\"Unexpected end of input; %s\" % (msg,))\n else:\n t = self.peek()\n raise ConfigParseError(\"Unexpected token %s; %s\" % (t, msg))\n"
] |
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
|
Grk0/python-libconf
|
libconf.py
|
TokenStream.error
|
python
|
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
|
Raise a ConfigParseError at the current input position
|
train
|
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L321-L327
|
[
"def finished(self):\n '''Return ``True`` if the end of the token stream is reached.'''\n return self.position >= len(self.tokens)\n"
] |
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup._get_valididty
|
python
|
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
|
Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L270-L294
| null |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.get_attribute
|
python
|
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
|
Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L296-L322
|
[
"def get_attributes(self, no_cache=False):\n \"\"\"\n Returns a dictionary of this group's attributes. This method caches the attributes after\n the first search unless no_cache is specified.\n\n :param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of\n from the cache. Default False\n :type no_cache: boolean\n\n \"\"\"\n\n if not self.attributes:\n self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],\n search_filter=self.ATTRIBUTES_SEARCH['filter_string'],\n search_scope=self.ATTRIBUTES_SEARCH['scope'],\n attributes=self.ATTRIBUTES_SEARCH['attribute_list'])\n\n results = [\n result[\"attributes\"] for result in self.ldap_connection.response if result[\"type\"] == \"searchResEntry\"\n ]\n\n if len(results) != 1:\n logger.debug(\"Search returned {count} results: {results}\".format(count=len(results), results=results))\n\n if results:\n self.attributes = results[0]\n else:\n self.attributes = []\n\n return self.attributes\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.get_attributes
|
python
|
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
|
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L324-L353
| null |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup._get_user_dn
|
python
|
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
|
Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L355-L381
|
[
"def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup._get_group_dn
|
python
|
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
|
Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L383-L409
|
[
"def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup._get_group_members
|
python
|
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
|
Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L411-L431
|
[
"def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.get_member_info
|
python
|
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
|
Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L433-L462
|
[
"def _get_group_members(self, page_size=500):\n \"\"\" Searches for a group and retrieve its members.\n\n :param page_size (optional): Many servers have a limit on the number of results that can be returned.\n Paged searches circumvent that limit. Adjust the page_size to be below the\n server's size limit. (default: 500)\n :type page_size: int\n\n \"\"\"\n\n entry_list = self.ldap_connection.extend.standard.paged_search(\n search_base=self.GROUP_MEMBER_SEARCH['base_dn'],\n search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),\n search_scope=self.GROUP_MEMBER_SEARCH['scope'],\n attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],\n paged_size=page_size\n )\n return [\n {\"dn\": result[\"dn\"], \"attributes\": result[\"attributes\"]}\n for result in entry_list if result[\"type\"] == \"searchResEntry\"\n ]\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.get_tree_members
|
python
|
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
|
Retrieves all members from this node of the tree down.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L464-L480
| null |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.add_member
|
python
|
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
|
Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L512-L528
|
[
"def _get_user_dn(self, user_lookup_attribute_value):\n \"\"\" Searches for a user and retrieves his distinguished name.\n\n :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE\n :type user_lookup_attribute_value: str\n\n :raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.\n\n \"\"\"\n self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],\n search_filter=self.USER_SEARCH['filter_string'].format(\n lookup_value=escape_query(user_lookup_attribute_value)),\n search_scope=self.USER_SEARCH['scope'],\n attributes=self.USER_SEARCH['attribute_list'])\n results = [result[\"dn\"] for result in self.ldap_connection.response if result[\"type\"] == \"searchResEntry\"]\n\n if not results:\n raise AccountDoesNotExist(\"The {user_lookup_attribute} provided does not exist in the Active \"\n \"Directory.\".format(user_lookup_attribute=self.user_lookup_attr))\n\n if len(results) > 1:\n logger.debug(\"Search returned more than one result: {results}\".format(results=results))\n\n if results:\n return results[0]\n else:\n return results\n",
"def _attempt_modification(self, target_type, target_identifier, modification):\n mod_type = list(modification.values())[0][0]\n action_word = \"adding\" if mod_type == MODIFY_ADD else \"removing\"\n action_prep = \"to\" if mod_type == MODIFY_ADD else \"from\"\n\n message_base = \"Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': \".format(\n action=action_word,\n target_type=target_type,\n target_id=target_identifier,\n prep=action_prep,\n group_dn=self.group_dn\n )\n\n try:\n self.ldap_connection.modify(dn=self.group_dn, changes=modification)\n except LDAPEntryAlreadyExistsResult:\n raise EntryAlreadyExists(\n message_base + \"The {target_type} already exists.\".format(target_type=target_type)\n )\n except LDAPInsufficientAccessRightsResult:\n raise InsufficientPermissions(\n message_base + \"The bind user does not have permission to modify this group.\"\n )\n except (LDAPException, LDAPExceptionError) as error_message:\n raise ModificationFailed(message_base + str(error_message))\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.remove_member
|
python
|
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
|
Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L530-L545
|
[
"def _get_user_dn(self, user_lookup_attribute_value):\n \"\"\" Searches for a user and retrieves his distinguished name.\n\n :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE\n :type user_lookup_attribute_value: str\n\n :raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.\n\n \"\"\"\n self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],\n search_filter=self.USER_SEARCH['filter_string'].format(\n lookup_value=escape_query(user_lookup_attribute_value)),\n search_scope=self.USER_SEARCH['scope'],\n attributes=self.USER_SEARCH['attribute_list'])\n results = [result[\"dn\"] for result in self.ldap_connection.response if result[\"type\"] == \"searchResEntry\"]\n\n if not results:\n raise AccountDoesNotExist(\"The {user_lookup_attribute} provided does not exist in the Active \"\n \"Directory.\".format(user_lookup_attribute=self.user_lookup_attr))\n\n if len(results) > 1:\n logger.debug(\"Search returned more than one result: {results}\".format(results=results))\n\n if results:\n return results[0]\n else:\n return results\n",
"def _attempt_modification(self, target_type, target_identifier, modification):\n mod_type = list(modification.values())[0][0]\n action_word = \"adding\" if mod_type == MODIFY_ADD else \"removing\"\n action_prep = \"to\" if mod_type == MODIFY_ADD else \"from\"\n\n message_base = \"Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': \".format(\n action=action_word,\n target_type=target_type,\n target_id=target_identifier,\n prep=action_prep,\n group_dn=self.group_dn\n )\n\n try:\n self.ldap_connection.modify(dn=self.group_dn, changes=modification)\n except LDAPEntryAlreadyExistsResult:\n raise EntryAlreadyExists(\n message_base + \"The {target_type} already exists.\".format(target_type=target_type)\n )\n except LDAPInsufficientAccessRightsResult:\n raise InsufficientPermissions(\n message_base + \"The bind user does not have permission to modify this group.\"\n )\n except (LDAPException, LDAPExceptionError) as error_message:\n raise ModificationFailed(message_base + str(error_message))\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.add_child
|
python
|
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
|
Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L547-L563
|
[
"def _get_group_dn(self, group_lookup_attribute_value):\n \"\"\" Searches for a group and retrieves its distinguished name.\n\n :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE\n :type group_lookup_attribute_value: str\n\n :raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.\n\n \"\"\"\n self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],\n search_filter=self.GROUP_SEARCH['filter_string'].format(\n lookup_value=escape_query(group_lookup_attribute_value)),\n search_scope=self.GROUP_SEARCH['scope'],\n attributes=self.GROUP_SEARCH['attribute_list'])\n results = [result[\"dn\"] for result in self.ldap_connection.response if result[\"type\"] == \"searchResEntry\"]\n\n if not results:\n raise GroupDoesNotExist(\"The {group_lookup_attribute} provided does not exist in the Active \"\n \"Directory.\".format(group_lookup_attribute=self.group_lookup_attr))\n\n if len(results) > 1:\n logger.debug(\"Search returned more than one result: {results}\".format(results=results))\n\n if results:\n return results[0]\n else:\n return results\n",
"def _attempt_modification(self, target_type, target_identifier, modification):\n mod_type = list(modification.values())[0][0]\n action_word = \"adding\" if mod_type == MODIFY_ADD else \"removing\"\n action_prep = \"to\" if mod_type == MODIFY_ADD else \"from\"\n\n message_base = \"Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': \".format(\n action=action_word,\n target_type=target_type,\n target_id=target_identifier,\n prep=action_prep,\n group_dn=self.group_dn\n )\n\n try:\n self.ldap_connection.modify(dn=self.group_dn, changes=modification)\n except LDAPEntryAlreadyExistsResult:\n raise EntryAlreadyExists(\n message_base + \"The {target_type} already exists.\".format(target_type=target_type)\n )\n except LDAPInsufficientAccessRightsResult:\n raise InsufficientPermissions(\n message_base + \"The bind user does not have permission to modify this group.\"\n )\n except (LDAPException, LDAPExceptionError) as error_message:\n raise ModificationFailed(message_base + str(error_message))\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.remove_child
|
python
|
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
|
Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L565-L581
|
[
"def _get_group_dn(self, group_lookup_attribute_value):\n \"\"\" Searches for a group and retrieves its distinguished name.\n\n :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE\n :type group_lookup_attribute_value: str\n\n :raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.\n\n \"\"\"\n self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],\n search_filter=self.GROUP_SEARCH['filter_string'].format(\n lookup_value=escape_query(group_lookup_attribute_value)),\n search_scope=self.GROUP_SEARCH['scope'],\n attributes=self.GROUP_SEARCH['attribute_list'])\n results = [result[\"dn\"] for result in self.ldap_connection.response if result[\"type\"] == \"searchResEntry\"]\n\n if not results:\n raise GroupDoesNotExist(\"The {group_lookup_attribute} provided does not exist in the Active \"\n \"Directory.\".format(group_lookup_attribute=self.group_lookup_attr))\n\n if len(results) > 1:\n logger.debug(\"Search returned more than one result: {results}\".format(results=results))\n\n if results:\n return results[0]\n else:\n return results\n",
"def _attempt_modification(self, target_type, target_identifier, modification):\n mod_type = list(modification.values())[0][0]\n action_word = \"adding\" if mod_type == MODIFY_ADD else \"removing\"\n action_prep = \"to\" if mod_type == MODIFY_ADD else \"from\"\n\n message_base = \"Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': \".format(\n action=action_word,\n target_type=target_type,\n target_id=target_identifier,\n prep=action_prep,\n group_dn=self.group_dn\n )\n\n try:\n self.ldap_connection.modify(dn=self.group_dn, changes=modification)\n except LDAPEntryAlreadyExistsResult:\n raise EntryAlreadyExists(\n message_base + \"The {target_type} already exists.\".format(target_type=target_type)\n )\n except LDAPInsufficientAccessRightsResult:\n raise InsufficientPermissions(\n message_base + \"The bind user does not have permission to modify this group.\"\n )\n except (LDAPException, LDAPExceptionError) as error_message:\n raise ModificationFailed(message_base + str(error_message))\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.get_descendants
|
python
|
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
|
Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L587-L612
| null |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.get_children
|
python
|
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
|
Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L614-L666
|
[
"def get_attribute(self, attribute_name, no_cache=False):\n \"\"\" Gets the passed attribute of this group.\n\n :param attribute_name: The name of the attribute to get.\n :type attribute_name: str\n :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of\n from the cache. Default False.\n :type no_cache: boolean\n\n :returns: The attribute requested or None if the attribute is not set.\n\n \"\"\"\n\n attributes = self.get_attributes(no_cache)\n\n if attribute_name not in attributes:\n logger.debug(\"ADGroup {group_dn} does not have the attribute \"\n \"'{attribute}'.\".format(group_dn=self.group_dn, attribute=attribute_name))\n return None\n else:\n raw_attribute = attributes[attribute_name]\n\n # Pop one-item lists\n if len(raw_attribute) == 1:\n raw_attribute = raw_attribute[0]\n\n return raw_attribute\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.child
|
python
|
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
|
Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L668-L714
|
[
"def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n",
"def get_attribute(self, attribute_name, no_cache=False):\n \"\"\" Gets the passed attribute of this group.\n\n :param attribute_name: The name of the attribute to get.\n :type attribute_name: str\n :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of\n from the cache. Default False.\n :type no_cache: boolean\n\n :returns: The attribute requested or None if the attribute is not set.\n\n \"\"\"\n\n attributes = self.get_attributes(no_cache)\n\n if attribute_name not in attributes:\n logger.debug(\"ADGroup {group_dn} does not have the attribute \"\n \"'{attribute}'.\".format(group_dn=self.group_dn, attribute=attribute_name))\n return None\n else:\n raw_attribute = attributes[attribute_name]\n\n # Pop one-item lists\n if len(raw_attribute) == 1:\n raw_attribute = raw_attribute[0]\n\n return raw_attribute\n"
] |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.parent
|
python
|
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
Returns this group's parent (up to the DC)
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L716-L729
| null |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/groups.py
|
ADGroup.ancestor
|
python
|
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L731-L756
| null |
class ADGroup:
"""
An Active Directory group.
This methods in this class can add members to, remove members from, and view members of an Active Directory group,
as well as traverse the Active Directory tree.
"""
def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None, group_lookup_attr=None,
attr_list=None, bind_dn=None, bind_password=None, user_search_base_dn=None,
group_search_base_dn=None):
""" Create an AD group object and establish an ldap search connection.
Any arguments other than group_dn are pulled from django settings
if they aren't passed in.
:param group_dn: The distinguished name of the active directory group to be modified.
:type group_dn: str
:param server_uri: (Required) The ldap server uri. Pulled from Django settings if None.
:type server_uri: str
:param base_dn: (Required) The ldap base dn. Pulled from Django settings if None.
:type base_dn: str
:param user_lookup_attr: The attribute used in user searches. Default is 'sAMAccountName'.
:type user_lookup_attr: str
:param group_lookup_attr: The attribute used in group searches. Default is 'name'.
:type group_lookup_attr: str
:param attr_list: A list of attributes to be pulled for each member of the AD group.
:type attr_list: list
:param bind_dn: A user used to bind to the AD. Necessary for any group modifications.
:type bind_dn: str
:param bind_password: The bind user's password. Necessary for any group modifications.
:type bind_password: str
:param user_search_base_dn: The base dn to use when performing a user search. Defaults to base_dn.
:type user_search_base_dn: str
:param group_search_base_dn: The base dn to use when performing a group search. Defaults to base_dn.
urrently unused.
:type group_search_base_dn: str
"""
# Attempt to grab settings from Django, fall back to init arguments if django is not used
try:
from django.conf import settings
except ImportError:
if not server_uri and not base_dn:
raise ImproperlyConfigured("A server_uri and base_dn must be passed as arguments if "
"django settings are not used.")
else:
self.server_uri = server_uri
self.base_dn = base_dn
self.user_lookup_attr = user_lookup_attr if user_lookup_attr else 'sAMAccountName'
self.group_lookup_attr = group_lookup_attr if group_lookup_attr else 'name'
self.attr_list = attr_list if attr_list else ['displayName', 'sAMAccountName', 'distinguishedName']
self.bind_dn = bind_dn
self.bind_password = bind_password
self.user_search_base_dn = user_search_base_dn if user_search_base_dn else self.base_dn
self.group_search_base_dn = group_search_base_dn if group_search_base_dn else self.base_dn
else:
if not server_uri:
if hasattr(settings, 'LDAP_GROUPS_SERVER_URI'):
self.server_uri = getattr(settings, 'LDAP_GROUPS_SERVER_URI')
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_SERVER_URI is not configured "
"in django settings file.")
else:
self.server_uri = server_uri
if not base_dn:
if hasattr(settings, 'LDAP_GROUPS_BASE_DN'):
self.base_dn = getattr(settings, 'LDAP_GROUPS_BASE_DN') if not base_dn else base_dn
else:
raise ImproperlyConfigured("LDAP Groups required setting LDAP_GROUPS_BASE_DN is not configured in "
"django settings file.")
else:
self.base_dn = base_dn
self.user_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE', 'sAMAccountName')
if not user_lookup_attr else user_lookup_attr
)
self.group_lookup_attr = (
getattr(settings, 'LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE', 'name')
if not group_lookup_attr else group_lookup_attr
)
self.attr_list = (
getattr(settings, 'LDAP_GROUPS_ATTRIBUTE_LIST', ['displayName', 'sAMAccountName', 'distinguishedName'])
if not attr_list else attr_list
)
self.bind_dn = getattr(settings, 'LDAP_GROUPS_BIND_DN', None) if not bind_dn else bind_dn
self.bind_password = (
getattr(settings, 'LDAP_GROUPS_BIND_PASSWORD', None)
if not bind_password else bind_password
)
self.user_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_USER_SEARCH_BASE_DN', self.base_dn)
if not user_search_base_dn else user_search_base_dn
)
self.group_search_base_dn = (
getattr(settings, 'LDAP_GROUPS_GROUP_SEARCH_BASE_DN', self.base_dn)
if not group_search_base_dn else group_search_base_dn
)
self.group_dn = group_dn
self.attributes = []
# Initialize search objects
self.ATTRIBUTES_SEARCH = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': ALL_ATTRIBUTES
}
self.USER_SEARCH = {
'base_dn': self.user_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=user)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.user_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SEARCH = {
'base_dn': self.group_search_base_dn,
'scope': SUBTREE,
'filter_string': ("(&(objectClass=group)({lookup_attribute}"
"={{lookup_value}}))").format(lookup_attribute=escape_query(self.group_lookup_attr)),
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_MEMBER_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': "(&(objectCategory=user)(memberOf={group_dn}))",
'attribute_list': self.attr_list
}
self.GROUP_CHILDREN_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(|(objectClass=group)(objectClass=organizationalUnit))"
"(memberOf={group_dn}))").format(group_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_CHILDREN_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.GROUP_SINGLE_CHILD_SEARCH = {
'base_dn': self.base_dn,
'scope': SUBTREE,
'filter_string': ("(&(&(|(objectClass=group)(objectClass=organizationalUnit))(name={{child_group_name}}))"
"(memberOf={parent_dn}))").format(parent_dn=escape_query(self.group_dn)),
'attribute_list': NO_ATTRIBUTES
}
self.OU_SINGLE_CHILD_SEARCH = {
'base_dn': self.group_dn,
'scope': LEVEL,
'filter_string': "(&(|(objectClass=group)(objectClass=organizationalUnit))(name={child_group_name}))",
'attribute_list': NO_ATTRIBUTES
}
self.DESCENDANT_SEARCH = {
'base_dn': self.group_dn,
'scope': SUBTREE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
self.VALID_GROUP_TEST = {
'base_dn': self.group_dn,
'scope': BASE,
'filter_string': "(|(objectClass=group)(objectClass=organizationalUnit))",
'attribute_list': NO_ATTRIBUTES
}
ldap_server = Server(self.server_uri)
if self.bind_dn and self.bind_password:
try:
self.ldap_connection = Connection(
ldap_server,
auto_bind=True,
user=self.bind_dn,
password=self.bind_password,
raise_exceptions=True
)
except LDAPInvalidServerError:
raise LDAPServerUnreachable("The LDAP server is down or the SERVER_URI is invalid.")
except LDAPInvalidCredentialsResult:
raise InvalidCredentials("The SERVER_URI, BIND_DN, or BIND_PASSWORD provided is not valid.")
else:
logger.warning("LDAP Bind Credentials are not set. Group modification methods will most likely fail.")
self.ldap_connection = Connection(ldap_server, auto_bind=True, raise_exceptions=True)
# Make sure the group is valid
valid, reason = self._get_valididty()
if not valid:
raise InvalidGroupDN("The AD Group distinguished name provided is invalid:"
"\n\t{reason}".format(reason=reason))
def __enter__(self):
return self
def __exit__(self):
self.__del__()
def __del__(self):
"""Closes the LDAP connection."""
self.ldap_connection.unbind()
def __repr__(self):
try:
return "<ADGroup: " + str(self.group_dn.split(",", 1)[0]) + ">"
except AttributeError:
return "<ADGroup: " + str(self.group_dn) + ">"
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.group_dn == other.group_dn)
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.group_dn < other.group_dn
def __hash__(self):
return hash(self.group_dn)
###############################################################################################################
# Group Information Methods #
###############################################################################################################
def _get_valididty(self):
""" Determines whether this AD Group is valid.
:returns: True and "" if this group is valid or False and a string description
with the reason why it isn't valid otherwise.
"""
try:
self.ldap_connection.search(search_base=self.VALID_GROUP_TEST['base_dn'],
search_filter=self.VALID_GROUP_TEST['filter_string'],
search_scope=self.VALID_GROUP_TEST['scope'],
attributes=self.VALID_GROUP_TEST['attribute_list'])
except LDAPOperationsErrorResult as error_message:
raise ImproperlyConfigured("The LDAP server most-likely does not accept anonymous connections:"
"\n\t{error}".format(error=error_message[0]['info']))
except LDAPInvalidDNSyntaxResult:
return False, "Invalid DN Syntax: {group_dn}".format(group_dn=self.group_dn)
except LDAPNoSuchObjectResult:
return False, "No such group: {group_dn}".format(group_dn=self.group_dn)
except LDAPSizeLimitExceededResult:
return False, ("This group has too many children for ldap-groups to handle: "
"{group_dn}".format(group_dn=self.group_dn))
return True, ""
def get_attribute(self, attribute_name, no_cache=False):
""" Gets the passed attribute of this group.
:param attribute_name: The name of the attribute to get.
:type attribute_name: str
:param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of
from the cache. Default False.
:type no_cache: boolean
:returns: The attribute requested or None if the attribute is not set.
"""
attributes = self.get_attributes(no_cache)
if attribute_name not in attributes:
logger.debug("ADGroup {group_dn} does not have the attribute "
"'{attribute}'.".format(group_dn=self.group_dn, attribute=attribute_name))
return None
else:
raw_attribute = attributes[attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
return raw_attribute
def get_attributes(self, no_cache=False):
"""
Returns a dictionary of this group's attributes. This method caches the attributes after
the first search unless no_cache is specified.
:param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of
from the cache. Default False
:type no_cache: boolean
"""
if not self.attributes:
self.ldap_connection.search(search_base=self.ATTRIBUTES_SEARCH['base_dn'],
search_filter=self.ATTRIBUTES_SEARCH['filter_string'],
search_scope=self.ATTRIBUTES_SEARCH['scope'],
attributes=self.ATTRIBUTES_SEARCH['attribute_list'])
results = [
result["attributes"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"
]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
self.attributes = results[0]
else:
self.attributes = []
return self.attributes
def _get_user_dn(self, user_lookup_attribute_value):
""" Searches for a user and retrieves his distinguished name.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.USER_SEARCH['base_dn'],
search_filter=self.USER_SEARCH['filter_string'].format(
lookup_value=escape_query(user_lookup_attribute_value)),
search_scope=self.USER_SEARCH['scope'],
attributes=self.USER_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise AccountDoesNotExist("The {user_lookup_attribute} provided does not exist in the Active "
"Directory.".format(user_lookup_attribute=self.user_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_dn(self, group_lookup_attribute_value):
""" Searches for a group and retrieves its distinguished name.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
"""
self.ldap_connection.search(search_base=self.GROUP_SEARCH['base_dn'],
search_filter=self.GROUP_SEARCH['filter_string'].format(
lookup_value=escape_query(group_lookup_attribute_value)),
search_scope=self.GROUP_SEARCH['scope'],
attributes=self.GROUP_SEARCH['attribute_list'])
results = [result["dn"] for result in self.ldap_connection.response if result["type"] == "searchResEntry"]
if not results:
raise GroupDoesNotExist("The {group_lookup_attribute} provided does not exist in the Active "
"Directory.".format(group_lookup_attribute=self.group_lookup_attr))
if len(results) > 1:
logger.debug("Search returned more than one result: {results}".format(results=results))
if results:
return results[0]
else:
return results
def _get_group_members(self, page_size=500):
""" Searches for a group and retrieve its members.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.GROUP_MEMBER_SEARCH['base_dn'],
search_filter=self.GROUP_MEMBER_SEARCH['filter_string'].format(group_dn=escape_query(self.group_dn)),
search_scope=self.GROUP_MEMBER_SEARCH['scope'],
attributes=self.GROUP_MEMBER_SEARCH['attribute_list'],
paged_size=page_size
)
return [
{"dn": result["dn"], "attributes": result["attributes"]}
for result in entry_list if result["type"] == "searchResEntry"
]
def get_member_info(self, page_size=500):
""" Retrieves member information from the AD group object.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
:returns: A dictionary of information on members of the AD group based on the LDAP_GROUPS_ATTRIBUTE_LIST
setting or attr_list argument.
"""
member_info = []
for member in self._get_group_members(page_size):
info_dict = {}
for attribute_name in member["attributes"]:
raw_attribute = member["attributes"][attribute_name]
# Pop one-item lists
if len(raw_attribute) == 1:
raw_attribute = raw_attribute[0]
info_dict.update({attribute_name: raw_attribute})
member_info.append(info_dict)
return member_info
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
members.extend(node.get_member_info())
queue.extendleft(node.get_children())
visited.add(node)
return [{attribute: member.get(attribute) for attribute in self.attr_list} for member in members if member]
###############################################################################################################
# Group Modification Methods #
###############################################################################################################
def _attempt_modification(self, target_type, target_identifier, modification):
mod_type = list(modification.values())[0][0]
action_word = "adding" if mod_type == MODIFY_ADD else "removing"
action_prep = "to" if mod_type == MODIFY_ADD else "from"
message_base = "Error {action} {target_type} '{target_id}' {prep} group '{group_dn}': ".format(
action=action_word,
target_type=target_type,
target_id=target_identifier,
prep=action_prep,
group_dn=self.group_dn
)
try:
self.ldap_connection.modify(dn=self.group_dn, changes=modification)
except LDAPEntryAlreadyExistsResult:
raise EntryAlreadyExists(
message_base + "The {target_type} already exists.".format(target_type=target_type)
)
except LDAPInsufficientAccessRightsResult:
raise InsufficientPermissions(
message_base + "The bind user does not have permission to modify this group."
)
except (LDAPException, LDAPExceptionError) as error_message:
raise ModificationFailed(message_base + str(error_message))
def add_member(self, user_lookup_attribute_value):
""" Attempts to add a member to the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **EntryAlreadyExists** if the account already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_member = {'member': (MODIFY_ADD, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, add_member)
def remove_member(self, user_lookup_attribute_value):
""" Attempts to remove a member from the AD group.
:param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE.
:type user_lookup_attribute_value: str
:raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory.
(inherited from _get_user_dn)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_member = {'member': (MODIFY_DELETE, [self._get_user_dn(user_lookup_attribute_value)])}
self._attempt_modification("member", user_lookup_attribute_value, remove_member)
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
add_child = {'member': (MODIFY_ADD, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, add_child)
def remove_child(self, group_lookup_attribute_value):
""" Attempts to remove a child from the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory.
(inherited from _get_group_dn)
:raises: **EntryAlreadyExists** if the child already exists in this group. (subclass of ModificationFailed)
:raises: **InsufficientPermissions** if the bind user does not have permission to modify this group.
(subclass of ModificationFailed)
:raises: **ModificationFailed** if the modification could not be performed for an unforseen reason.
"""
remove_child = {'member': (MODIFY_DELETE, [self._get_group_dn(group_lookup_attribute_value)])}
self._attempt_modification("child", group_lookup_attribute_value, remove_child)
###################################################################################################################
# Group Traversal Methods #
###################################################################################################################
def get_descendants(self, page_size=500):
""" Returns a list of all descendants of this group.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=self.DESCENDANT_SEARCH['base_dn'],
search_filter=self.DESCENDANT_SEARCH['filter_string'],
search_scope=self.DESCENDANT_SEARCH['scope'],
attributes=self.DESCENDANT_SEARCH['attribute_list'],
paged_size=page_size
)
return [
ADGroup(
group_dn=entry["dn"], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
) for entry in entry_list if entry["type"] == "searchResEntry"
]
def get_children(self, page_size=500):
""" Returns a list of this group's children.
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
children = []
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_CHILDREN_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_CHILDREN_SEARCH
else:
logger.debug("Unable to process children of group {group_dn} with type {group_type}.".format(
group_dn=self.group_dn,
group_type=group_type
))
return []
try:
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'],
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
except LDAPInvalidFilterError:
logger.debug("Invalid Filter!: {filter}".format(filter=connection_dict['filter_string']))
return []
else:
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
for result in results:
children.append(
ADGroup(
group_dn=result, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn,
group_search_base_dn=self.user_search_base_dn
)
)
return children
def child(self, group_name, page_size=500):
""" Returns the child ad group that matches the provided group_name or none if the child does not exist.
:param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU='
:type group_name: str
:param page_size (optional): Many servers have a limit on the number of results that can be returned.
Paged searches circumvent that limit. Adjust the page_size to be below the
server's size limit. (default: 500)
:type page_size: int
"""
object_class = self.get_attribute("objectClass")
group_type = object_class[-1] if object_class else None
if group_type == "group":
connection_dict = self.GROUP_SINGLE_CHILD_SEARCH
elif group_type == "organizationalUnit":
connection_dict = self.OU_SINGLE_CHILD_SEARCH
else:
logger.debug("Unable to process child {child} of group {group_dn} with type {group_type}.".format(
child=group_name, group_dn=self.group_dn, group_type=group_type
))
return []
entry_list = self.ldap_connection.extend.standard.paged_search(
search_base=connection_dict['base_dn'],
search_filter=connection_dict['filter_string'].format(child_group_name=escape_query(group_name)),
search_scope=connection_dict['scope'],
attributes=connection_dict['attribute_list'],
paged_size=page_size
)
results = [result["dn"] for result in entry_list if result["type"] == "searchResEntry"]
if len(results) != 1:
logger.debug("Search returned {count} results: {results}".format(count=len(results), results=results))
if results:
return ADGroup(
group_dn=results[0], server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
else:
return None
def parent(self):
""" Returns this group's parent (up to the DC)"""
# Don't go above the DC
if ''.join(self.group_dn.split("DC")[0].split()) == '':
return self
else:
parent_dn = self.group_dn.split(",", 1).pop()
return ADGroup(
group_dn=parent_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
def ancestor(self, generation):
""" Returns an ancestor of this group given a generation (up to the DC).
:param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ...
:type generation: int
"""
# Don't go below the current generation and don't go above the DC
if generation < 1:
return self
else:
ancestor_dn = self.group_dn
for _index in range(generation):
if ''.join(ancestor_dn.split("DC")[0].split()) == '':
break
else:
ancestor_dn = ancestor_dn.split(",", 1).pop()
return ADGroup(
group_dn=ancestor_dn, server_uri=self.server_uri, base_dn=self.base_dn,
user_lookup_attr=self.user_lookup_attr, group_lookup_attr=self.group_lookup_attr,
attr_list=self.attr_list, bind_dn=self.bind_dn, bind_password=self.bind_password,
user_search_base_dn=self.user_search_base_dn, group_search_base_dn=self.user_search_base_dn
)
|
kavdev/ldap-groups
|
ldap_groups/utils.py
|
escape_query
|
python
|
def escape_query(query):
return query.replace("\\", r"\5C").replace("*", r"\2A").replace("(", r"\28").replace(")", r"\29")
|
Escapes certain filter characters from an LDAP query.
|
train
|
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/utils.py#L23-L26
| null |
"""
.. module:: ldap_groups.utils
:synopsis: LDAP Groups Utilities.
ldap-groups is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ldap-groups is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser Public License for more details.
You should have received a copy of the GNU Lesser Public License
along with ldap-groups. If not, see <http://www.gnu.org/licenses/>.
.. moduleauthor:: Alex Kavanaugh <kavanaugh.development@outlook.com>
"""
|
inveniosoftware-contrib/json-merger
|
json_merger/utils.py
|
dedupe_list
|
python
|
def dedupe_list(l):
result = []
for el in l:
if el not in result:
result.append(el)
return result
|
Remove duplicates from a list preserving the order.
We might be tempted to use the list(set(l)) idiom, but it doesn't preserve
the order, which hinders testability and does not work for lists with
unhashable elements.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/utils.py#L107-L120
| null |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
from .nothing import NOTHING
def get_obj_at_key_path(obj, key_path, default=None):
current = obj
for k in key_path:
try:
current = current[k]
except (KeyError, IndexError, TypeError):
return default
return current
def set_obj_at_key_path(obj, key_path, value, raise_key_error=True):
try:
return _set_obj_at_key_path(obj, key_path, value)
except KeyError as e:
if raise_key_error:
raise e
else:
return obj
def _set_obj_at_key_path(obj, key_path, value):
# We are setting the obj param to another value.
if len(key_path) == 0:
return value
# Try to get the parent of the object to be set.
parent = get_obj_at_key_path(obj, key_path[:-1], NOTHING)
if parent == NOTHING:
raise KeyError(key_path)
try:
parent[key_path[-1]] = value
except (KeyError, IndexError, TypeError):
raise KeyError(key_path)
return obj
def del_obj_at_key_path(obj, key_path, raise_key_error=True):
obj = get_obj_at_key_path(obj, key_path[:-1], NOTHING)
if obj != NOTHING:
try:
del obj[key_path[-1]]
except (KeyError, IndexError, TypeError):
if raise_key_error:
raise KeyError(key_path)
elif raise_key_error:
raise KeyError(key_path)
def has_prefix(key_path, prefix):
return len(prefix) <= len(key_path) and key_path[:len(prefix)] == prefix
def remove_prefix(key_path, prefix):
if not has_prefix(key_path, prefix):
raise ValueError('Bad Prefix {}'.format(prefix))
return key_path[len(prefix):]
def get_dotted_key_path(key_path, filter_int_keys=False):
return '.'.join(k for k in key_path
if not isinstance(k, int) and filter_int_keys)
def get_conf_set_for_key_path(conf_set, key_path):
prefix = get_dotted_key_path(key_path, True)
return set(remove_prefix(k, prefix).lstrip('.')
for k in conf_set if has_prefix(k, prefix))
def force_list(data):
if not isinstance(data, (list, tuple, set)):
return [data]
elif isinstance(data, (tuple, set)):
return list(data)
return data
|
inveniosoftware-contrib/json-merger
|
json_merger/config.py
|
DictMergerOps.keep_longest
|
python
|
def keep_longest(head, update, down_path):
if update is None:
return 'f'
if head is None:
return 's'
return 'f' if len(head) >= len(update) else 's'
|
Keep longest field among `head` and `update`.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/config.py#L40-L48
| null |
class DictMergerOps(object):
"""Possible strategies for merging two base values.
Attributes:
FALLBACK_KEEP_HEAD: In case of conflict keep the `head` value.
FALLBACK_KEEP_UPDATE: In case of conflict keep the `update` value.
"""
allowed_ops = [
'FALLBACK_KEEP_HEAD',
'FALLBACK_KEEP_UPDATE'
]
@staticmethod
|
inveniosoftware-contrib/json-merger
|
json_merger/graph_builder.py
|
toposort
|
python
|
def toposort(graph, pick_first='head'):
in_deg = {}
for node, next_nodes in six.iteritems(graph):
for next_node in [next_nodes.head_node, next_nodes.update_node]:
if next_node is None:
continue
in_deg[next_node] = in_deg.get(next_node, 0) + 1
stk = [FIRST]
ordered = []
visited = set()
while stk:
node = stk.pop()
visited.add(node)
if node != FIRST:
ordered.append(node)
traversal = _get_traversal(graph.get(node, BeforeNodes()), pick_first)
for next_node in traversal:
if next_node is None:
continue
if next_node in visited:
raise ValueError('Graph has a cycle')
in_deg[next_node] -= 1
if in_deg[next_node] == 0:
stk.append(next_node)
# Nodes may not be walked because they don't reach in degree 0.
if len(ordered) != len(graph) - 1:
raise ValueError('Graph has a cycle')
return ordered
|
Toplogically sorts a list match graph.
Tries to perform a topological sort using as tiebreaker the pick_first
argument. If the graph contains cycles, raise ValueError.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/graph_builder.py#L231-L266
|
[
"def _get_traversal(next_nodes, pick_first):\n if pick_first == 'head':\n return [next_nodes.update_node, next_nodes.head_node]\n else:\n return [next_nodes.head_node, next_nodes.update_node]\n"
] |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
from collections import deque
import six
from .comparator import DefaultComparator
from .nothing import NOTHING
from .stats import ListMatchStats
FIRST = 'first'
class BeforeNodes(object):
"""Edge in the match graph."""
def __init__(self, head_node=None, update_node=None):
self.head_node = head_node
self.update_node = update_node
def __repr__(self):
return 'BeforeNodes <head_node: {}, update_node: {}>'.format(
self.head_node, self.update_node)
class ListMatchGraphBuilder(object):
def __init__(self, root, head, update, sources,
comparator_cls=DefaultComparator):
self.root = root
self.head = head
self.update = update
self.sources = sources
self.root_head_comparator = comparator_cls(self.root, self.head)
self.root_update_comparator = comparator_cls(self.root, self.update)
self.head_update_comparator = comparator_cls(self.head, self.update)
# Keys are (target, source), values are comparator_instance and
# the source list from which to search.
self.comparators = {
('root', 'head'): (self.root_head_comparator, 'l2'),
('head', 'root'): (self.root_head_comparator, 'l1'),
('root', 'update'): (self.root_update_comparator, 'l2'),
('update', 'root'): (self.root_update_comparator, 'l1'),
('head', 'update'): (self.head_update_comparator, 'l2'),
('update', 'head'): (self.head_update_comparator, 'l1'),
}
self.node_data = {}
self.graph = {}
self.head_stats = ListMatchStats(head, root)
self.update_stats = ListMatchStats(update, root)
self._node_src_indices = {}
self._head_idx_to_node = {}
self._update_idx_to_node = {}
self._dirty_nodes = set()
self._next_node_id = 0
self.multiple_match_choice_idx = set()
self.multiple_match_choices = []
def _new_node_id(self):
node_id = self._next_node_id
self._next_node_id += 1
return node_id
def _push_node(self, root_elem, head_elem, update_elem):
root_idx, root_obj = root_elem
head_idx, head_obj = head_elem
update_idx, update_obj = update_elem
node_id = self._new_node_id()
self.node_data[node_id] = (root_obj, head_obj, update_obj)
self._node_src_indices[node_id] = (root_idx, head_idx, update_idx)
if head_idx >= 0:
self._head_idx_to_node[head_idx] = node_id
if update_idx >= 0:
self._update_idx_to_node[update_idx] = node_id
def _get_matches(self, source, source_idx, source_obj):
other_two = {'head': ['root', 'update'],
'update': ['root', 'head'],
'root': ['head', 'update']}
indices = {'root': {}, 'head': {}, 'update': {}}
indices[source][source_idx] = source_obj
# Start a BFS of matching elements.
q = deque([(source, source_idx)])
while q:
curr_src, curr_idx = q.popleft()
for target in other_two[curr_src]:
comparator, cmp_list = self.comparators[(target, curr_src)]
# cmp_list is either 'l1' or 'l2'
# (the paremeter for the comparator class convetion)
matches = comparator.get_matches(cmp_list, curr_idx)
for target_idx, target_obj in matches:
if target_idx in indices[target]:
continue
indices[target][target_idx] = target_obj
q.append((target, target_idx))
result = {}
for lst, res_indices in indices.items():
if not res_indices:
result[lst] = [(-1, NOTHING)]
else:
result[lst] = sorted(res_indices.items())
return result['root'], result['head'], result['update']
def _add_matches(self, root_elems, head_elems, update_elems):
matches = [(r, h, u)
for r in root_elems
for h in head_elems
for u in update_elems]
if len(matches) == 1:
self._push_node(*matches[0])
else:
self.multiple_match_choice_idx.update([(r[0], h[0], u[0])
for r, h, u in matches])
def _populate_nodes(self):
for idx, obj in enumerate(self.head):
r_elems, h_elems, u_elems = self._get_matches('head', idx, obj)
if 'head' in self.sources:
self._add_matches(r_elems, h_elems, u_elems)
if len(r_elems) == 1 and r_elems[0][0] >= 0:
self.head_stats.add_root_match(idx, r_elems[0][0])
for idx, obj in enumerate(self.update):
r_elems, h_elems, u_elems = self._get_matches('update', idx, obj)
# Only add the node to the graph only if not already added.
if ('update' in self.sources and
idx not in self._update_idx_to_node):
self._add_matches(r_elems, h_elems, u_elems)
if len(r_elems) == 1 and r_elems[0][0] >= 0:
self.update_stats.add_root_match(idx, r_elems[0][0])
# Add stats from built nodes.
for root_idx, head_idx, update_idx in self._node_src_indices.values():
if head_idx >= 0:
self.head_stats.move_to_result(head_idx)
if update_idx >= 0:
self.update_stats.move_to_result(update_idx)
# Move the unique multiple match indices to conflicts.
for r_idx, h_idx, u_idx in self.multiple_match_choice_idx:
r_obj = self.root[r_idx] if r_idx >= 0 else None
h_obj = self.head[h_idx] if h_idx >= 0 else None
u_obj = self.update[u_idx] if u_idx >= 0 else None
self.multiple_match_choices.append((r_obj, h_obj, u_obj))
def _get_next_node(self, source, indices):
if source not in self.sources:
return None
idx_to_node = {
'head': self._head_idx_to_node,
'update': self._update_idx_to_node
}[source]
for idx in indices:
if idx in idx_to_node:
return idx_to_node[idx]
return None
def build_graph(self):
self._populate_nodes()
# Link a dummy first node before the first element of the sources
# lists.
self.node_data[FIRST] = (NOTHING, NOTHING, NOTHING)
self.graph[FIRST] = BeforeNodes()
next_head_node = self._get_next_node('head', range(len(self.head)))
next_update_node = self._get_next_node('update',
range(len(self.update)))
self.graph[FIRST].head_node = next_head_node
self.graph[FIRST].update_node = next_update_node
# Link any other nodes with the elements that come after them in their
# source lists.
for node_id, node_indices in six.iteritems(self._node_src_indices):
root_idx, head_idx, update_idx = node_indices
head_next_l = []
update_next_l = []
if head_idx >= 0:
head_next_l = range(head_idx + 1, len(self.head))
if update_idx >= 0:
update_next_l = range(update_idx + 1, len(self.update))
next_head_node = self._get_next_node('head', head_next_l)
next_update_node = self._get_next_node('update', update_next_l)
self.graph[node_id] = BeforeNodes(next_head_node, next_update_node)
return self.graph, self.node_data
def _get_traversal(next_nodes, pick_first):
if pick_first == 'head':
return [next_nodes.update_node, next_nodes.head_node]
else:
return [next_nodes.head_node, next_nodes.update_node]
def sort_cyclic_graph_best_effort(graph, pick_first='head'):
"""Fallback for cases in which the graph has cycles."""
ordered = []
visited = set()
# Go first on the pick_first chain then go back again on the others
# that were not visited. Given the way the graph is built both chains
# will always contain all the elements.
if pick_first == 'head':
fst_attr, snd_attr = ('head_node', 'update_node')
else:
fst_attr, snd_attr = ('update_node', 'head_node')
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], fst_attr)
if current not in visited and current is not None:
ordered.append(current)
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], snd_attr)
if current not in visited and current is not None:
ordered.append(current)
return ordered
|
inveniosoftware-contrib/json-merger
|
json_merger/graph_builder.py
|
sort_cyclic_graph_best_effort
|
python
|
def sort_cyclic_graph_best_effort(graph, pick_first='head'):
ordered = []
visited = set()
# Go first on the pick_first chain then go back again on the others
# that were not visited. Given the way the graph is built both chains
# will always contain all the elements.
if pick_first == 'head':
fst_attr, snd_attr = ('head_node', 'update_node')
else:
fst_attr, snd_attr = ('update_node', 'head_node')
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], fst_attr)
if current not in visited and current is not None:
ordered.append(current)
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], snd_attr)
if current not in visited and current is not None:
ordered.append(current)
return ordered
|
Fallback for cases in which the graph has cycles.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/graph_builder.py#L269-L293
| null |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
from collections import deque
import six
from .comparator import DefaultComparator
from .nothing import NOTHING
from .stats import ListMatchStats
FIRST = 'first'
class BeforeNodes(object):
"""Edge in the match graph."""
def __init__(self, head_node=None, update_node=None):
self.head_node = head_node
self.update_node = update_node
def __repr__(self):
return 'BeforeNodes <head_node: {}, update_node: {}>'.format(
self.head_node, self.update_node)
class ListMatchGraphBuilder(object):
def __init__(self, root, head, update, sources,
comparator_cls=DefaultComparator):
self.root = root
self.head = head
self.update = update
self.sources = sources
self.root_head_comparator = comparator_cls(self.root, self.head)
self.root_update_comparator = comparator_cls(self.root, self.update)
self.head_update_comparator = comparator_cls(self.head, self.update)
# Keys are (target, source), values are comparator_instance and
# the source list from which to search.
self.comparators = {
('root', 'head'): (self.root_head_comparator, 'l2'),
('head', 'root'): (self.root_head_comparator, 'l1'),
('root', 'update'): (self.root_update_comparator, 'l2'),
('update', 'root'): (self.root_update_comparator, 'l1'),
('head', 'update'): (self.head_update_comparator, 'l2'),
('update', 'head'): (self.head_update_comparator, 'l1'),
}
self.node_data = {}
self.graph = {}
self.head_stats = ListMatchStats(head, root)
self.update_stats = ListMatchStats(update, root)
self._node_src_indices = {}
self._head_idx_to_node = {}
self._update_idx_to_node = {}
self._dirty_nodes = set()
self._next_node_id = 0
self.multiple_match_choice_idx = set()
self.multiple_match_choices = []
def _new_node_id(self):
node_id = self._next_node_id
self._next_node_id += 1
return node_id
def _push_node(self, root_elem, head_elem, update_elem):
root_idx, root_obj = root_elem
head_idx, head_obj = head_elem
update_idx, update_obj = update_elem
node_id = self._new_node_id()
self.node_data[node_id] = (root_obj, head_obj, update_obj)
self._node_src_indices[node_id] = (root_idx, head_idx, update_idx)
if head_idx >= 0:
self._head_idx_to_node[head_idx] = node_id
if update_idx >= 0:
self._update_idx_to_node[update_idx] = node_id
def _get_matches(self, source, source_idx, source_obj):
other_two = {'head': ['root', 'update'],
'update': ['root', 'head'],
'root': ['head', 'update']}
indices = {'root': {}, 'head': {}, 'update': {}}
indices[source][source_idx] = source_obj
# Start a BFS of matching elements.
q = deque([(source, source_idx)])
while q:
curr_src, curr_idx = q.popleft()
for target in other_two[curr_src]:
comparator, cmp_list = self.comparators[(target, curr_src)]
# cmp_list is either 'l1' or 'l2'
# (the paremeter for the comparator class convetion)
matches = comparator.get_matches(cmp_list, curr_idx)
for target_idx, target_obj in matches:
if target_idx in indices[target]:
continue
indices[target][target_idx] = target_obj
q.append((target, target_idx))
result = {}
for lst, res_indices in indices.items():
if not res_indices:
result[lst] = [(-1, NOTHING)]
else:
result[lst] = sorted(res_indices.items())
return result['root'], result['head'], result['update']
def _add_matches(self, root_elems, head_elems, update_elems):
matches = [(r, h, u)
for r in root_elems
for h in head_elems
for u in update_elems]
if len(matches) == 1:
self._push_node(*matches[0])
else:
self.multiple_match_choice_idx.update([(r[0], h[0], u[0])
for r, h, u in matches])
def _populate_nodes(self):
for idx, obj in enumerate(self.head):
r_elems, h_elems, u_elems = self._get_matches('head', idx, obj)
if 'head' in self.sources:
self._add_matches(r_elems, h_elems, u_elems)
if len(r_elems) == 1 and r_elems[0][0] >= 0:
self.head_stats.add_root_match(idx, r_elems[0][0])
for idx, obj in enumerate(self.update):
r_elems, h_elems, u_elems = self._get_matches('update', idx, obj)
# Only add the node to the graph only if not already added.
if ('update' in self.sources and
idx not in self._update_idx_to_node):
self._add_matches(r_elems, h_elems, u_elems)
if len(r_elems) == 1 and r_elems[0][0] >= 0:
self.update_stats.add_root_match(idx, r_elems[0][0])
# Add stats from built nodes.
for root_idx, head_idx, update_idx in self._node_src_indices.values():
if head_idx >= 0:
self.head_stats.move_to_result(head_idx)
if update_idx >= 0:
self.update_stats.move_to_result(update_idx)
# Move the unique multiple match indices to conflicts.
for r_idx, h_idx, u_idx in self.multiple_match_choice_idx:
r_obj = self.root[r_idx] if r_idx >= 0 else None
h_obj = self.head[h_idx] if h_idx >= 0 else None
u_obj = self.update[u_idx] if u_idx >= 0 else None
self.multiple_match_choices.append((r_obj, h_obj, u_obj))
def _get_next_node(self, source, indices):
if source not in self.sources:
return None
idx_to_node = {
'head': self._head_idx_to_node,
'update': self._update_idx_to_node
}[source]
for idx in indices:
if idx in idx_to_node:
return idx_to_node[idx]
return None
def build_graph(self):
self._populate_nodes()
# Link a dummy first node before the first element of the sources
# lists.
self.node_data[FIRST] = (NOTHING, NOTHING, NOTHING)
self.graph[FIRST] = BeforeNodes()
next_head_node = self._get_next_node('head', range(len(self.head)))
next_update_node = self._get_next_node('update',
range(len(self.update)))
self.graph[FIRST].head_node = next_head_node
self.graph[FIRST].update_node = next_update_node
# Link any other nodes with the elements that come after them in their
# source lists.
for node_id, node_indices in six.iteritems(self._node_src_indices):
root_idx, head_idx, update_idx = node_indices
head_next_l = []
update_next_l = []
if head_idx >= 0:
head_next_l = range(head_idx + 1, len(self.head))
if update_idx >= 0:
update_next_l = range(update_idx + 1, len(self.update))
next_head_node = self._get_next_node('head', head_next_l)
next_update_node = self._get_next_node('update', update_next_l)
self.graph[node_id] = BeforeNodes(next_head_node, next_update_node)
return self.graph, self.node_data
def _get_traversal(next_nodes, pick_first):
if pick_first == 'head':
return [next_nodes.update_node, next_nodes.head_node]
else:
return [next_nodes.head_node, next_nodes.update_node]
def toposort(graph, pick_first='head'):
"""Toplogically sorts a list match graph.
Tries to perform a topological sort using as tiebreaker the pick_first
argument. If the graph contains cycles, raise ValueError.
"""
in_deg = {}
for node, next_nodes in six.iteritems(graph):
for next_node in [next_nodes.head_node, next_nodes.update_node]:
if next_node is None:
continue
in_deg[next_node] = in_deg.get(next_node, 0) + 1
stk = [FIRST]
ordered = []
visited = set()
while stk:
node = stk.pop()
visited.add(node)
if node != FIRST:
ordered.append(node)
traversal = _get_traversal(graph.get(node, BeforeNodes()), pick_first)
for next_node in traversal:
if next_node is None:
continue
if next_node in visited:
raise ValueError('Graph has a cycle')
in_deg[next_node] -= 1
if in_deg[next_node] == 0:
stk.append(next_node)
# Nodes may not be walked because they don't reach in degree 0.
if len(ordered) != len(graph) - 1:
raise ValueError('Graph has a cycle')
return ordered
|
inveniosoftware-contrib/json-merger
|
json_merger/dict_merger.py
|
patch_to_conflict_set
|
python
|
def patch_to_conflict_set(patch):
patch_type, patched_key, value = patch
if isinstance(patched_key, list):
key_path = tuple(patched_key)
else:
key_path = tuple(k for k in patched_key.split('.') if k)
conflicts = set()
if patch_type == REMOVE:
conflict_type = ConflictType.REMOVE_FIELD
for key, obj in value:
conflicts.add(Conflict(conflict_type, key_path + (key, ), None))
elif patch_type == CHANGE:
conflict_type = ConflictType.SET_FIELD
first_val, second_val = value
conflicts.add(Conflict(conflict_type, key_path, second_val))
elif patch_type == ADD:
conflict_type = ConflictType.SET_FIELD
for key, obj in value:
conflicts.add(Conflict(conflict_type, key_path + (key, ), obj))
return conflicts
|
Translates a dictdiffer conflict into a json_merger one.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/dict_merger.py#L54-L76
| null |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
import copy
from itertools import chain
import six
from dictdiffer import ADD, CHANGE, REMOVE, patch
from dictdiffer.merge import Merger, UnresolvedConflictsException
from .config import DictMergerOps
from .conflict import Conflict, ConflictType
from .errors import MergeError
from .nothing import NOTHING
from .utils import (
dedupe_list, del_obj_at_key_path, get_dotted_key_path, get_obj_at_key_path,
set_obj_at_key_path
)
def _get_list_fields(obj, res, key_path=()):
if isinstance(obj, list):
res.append(key_path)
elif isinstance(obj, dict):
for key, value in six.iteritems(obj):
_get_list_fields(value, res, key_path + (key, ))
return res
class SkipListsMerger(object):
"""3-way Merger that ignores list fields."""
def __init__(self, root, head, update, default_op,
data_lists=None, custom_ops={}, key_path=None):
self.root = copy.deepcopy(root)
self.head = copy.deepcopy(head)
self.update = copy.deepcopy(update)
self.custom_ops = custom_ops
self.default_op = self._operation_to_function(default_op)
self.data_lists = set(data_lists or [])
self.key_path = key_path or []
# We can have the same conflict appear more times because we keep only
# one of the possible resolutions as a conflict while we apply the
# other as a fallback. Sometimes multiple fallback dict diffs
# conflict with a single change.
self.conflict_set = set()
self.skipped_lists = set()
self.merged_root = None
self.list_backups = {}
def _build_skipped_lists(self):
lists = set()
lists.update(_get_list_fields(self.head, []))
lists.intersection_update(_get_list_fields(self.update, []))
for l in lists:
dotted = get_dotted_key_path(l, True)
if dotted not in self.data_lists:
self.skipped_lists.add(l)
def _backup_lists(self):
self._build_skipped_lists()
for l in self.skipped_lists:
self.list_backups[l] = (
get_obj_at_key_path(self.root, l),
get_obj_at_key_path(self.head, l),
get_obj_at_key_path(self.update, l))
# The root is the only one that may not be there. Head and update
# are retrieved using list intersection.
del_obj_at_key_path(self.root, l, False)
del_obj_at_key_path(self.head, l)
del_obj_at_key_path(self.update, l)
def _restore_lists(self):
for l, (bak_r, bak_h, bak_u) in six.iteritems(self.list_backups):
if bak_r is not None:
set_obj_at_key_path(self.root, l, bak_r)
set_obj_at_key_path(self.head, l, bak_h)
set_obj_at_key_path(self.update, l, bak_u)
@property
def conflicts(self):
"""List of conflicts for the current object."""
# Make this compatible with the project convention (list of conflicts).
return list(self.conflict_set)
def _merge_base_values(self):
if self.head == self.update:
self.merged_root = self.head
elif self.head == NOTHING:
self.merged_root = self.update
elif self.update == NOTHING:
self.merged_root = self.head
elif self.head == self.root:
self.merged_root = self.update
elif self.update == self.root:
self.merged_root = self.head
else:
strategy = self._get_rule_for_field(self.key_path)
self.merged_root, conflict = {
'f': (self.head, self.update),
's': (self.update, self.head)}[strategy]
self.conflict_set.add(
Conflict(ConflictType.SET_FIELD, (), conflict))
def _merge_dicts(self):
self._backup_lists()
non_list_merger = Merger(self.root, self.head, self.update, {})
try:
non_list_merger.run()
except UnresolvedConflictsException as e:
self._solve_dict_conflicts(non_list_merger, e.content)
self._restore_lists()
self.merged_root = patch(
dedupe_list(non_list_merger.unified_patches),
self.root
)
def _solve_dict_conflicts(self, non_list_merger, conflicts):
strategies = [self._get_custom_strategy(conflict)
for conflict in conflicts]
non_list_merger.continue_run(strategies)
for conflict, strategy in zip(conflicts, strategies):
conflict_patch = {'f': conflict.second_patch,
's': conflict.first_patch}[strategy]
self.conflict_set.update(patch_to_conflict_set(conflict_patch))
def _get_custom_strategy(self, patch):
full_path = self._get_path_from_patch(patch)
return self._get_rule_for_field(full_path)
@staticmethod
def _get_path_from_patch(patch):
_, field, modification = patch.first_patch
full_path = []
if isinstance(field, list):
full_path.extend(field)
elif field:
full_path.append(field)
if (isinstance(modification, list) and modification[0][0]):
full_path.append(modification[0][0])
return full_path
@staticmethod
def _operation_to_function(operation):
if callable(operation):
return operation
elif operation == DictMergerOps.FALLBACK_KEEP_HEAD:
return lambda head, update, down_path: 'f'
elif operation == DictMergerOps.FALLBACK_KEEP_UPDATE:
return lambda head, update, down_path: 's'
else:
return lambda head, update, down_path: None
def _absolute_path(self, field_path):
full_path = list(self.key_path) + field_path
return get_dotted_key_path(full_path, filter_int_keys=True)
def _get_rule_for_field(self, field_path):
current_path = self._absolute_path(field_path)
head = get_obj_at_key_path(self.head, field_path)
update = get_obj_at_key_path(self.update, field_path)
down_path = []
rule = None
while current_path:
operation = self._operation_to_function(
self.custom_ops.get(current_path)
)
rule = operation(head, update, down_path)
if rule:
break
current_path_parts = current_path.split('.')
current_path = '.'.join(current_path_parts[:-1])
down_path.append(current_path_parts[-1])
return rule or self.default_op(head, update, field_path)
def merge(self):
"""Perform merge of head and update starting from root."""
if isinstance(self.head, dict) and isinstance(self.update, dict):
if not isinstance(self.root, dict):
self.root = {}
self._merge_dicts()
else:
self._merge_base_values()
if self.conflict_set:
raise MergeError('Dictdiffer Errors', self.conflicts)
|
inveniosoftware-contrib/json-merger
|
json_merger/dict_merger.py
|
SkipListsMerger.merge
|
python
|
def merge(self):
if isinstance(self.head, dict) and isinstance(self.update, dict):
if not isinstance(self.root, dict):
self.root = {}
self._merge_dicts()
else:
self._merge_base_values()
if self.conflict_set:
raise MergeError('Dictdiffer Errors', self.conflicts)
|
Perform merge of head and update starting from root.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/dict_merger.py#L236-L246
|
[
"def _merge_base_values(self):\n if self.head == self.update:\n self.merged_root = self.head\n elif self.head == NOTHING:\n self.merged_root = self.update\n elif self.update == NOTHING:\n self.merged_root = self.head\n elif self.head == self.root:\n self.merged_root = self.update\n elif self.update == self.root:\n self.merged_root = self.head\n else:\n strategy = self._get_rule_for_field(self.key_path)\n self.merged_root, conflict = {\n 'f': (self.head, self.update),\n 's': (self.update, self.head)}[strategy]\n self.conflict_set.add(\n Conflict(ConflictType.SET_FIELD, (), conflict))\n",
"def _merge_dicts(self):\n self._backup_lists()\n\n non_list_merger = Merger(self.root, self.head, self.update, {})\n try:\n non_list_merger.run()\n except UnresolvedConflictsException as e:\n self._solve_dict_conflicts(non_list_merger, e.content)\n\n self._restore_lists()\n self.merged_root = patch(\n dedupe_list(non_list_merger.unified_patches),\n self.root\n )\n"
] |
class SkipListsMerger(object):
"""3-way Merger that ignores list fields."""
def __init__(self, root, head, update, default_op,
data_lists=None, custom_ops={}, key_path=None):
self.root = copy.deepcopy(root)
self.head = copy.deepcopy(head)
self.update = copy.deepcopy(update)
self.custom_ops = custom_ops
self.default_op = self._operation_to_function(default_op)
self.data_lists = set(data_lists or [])
self.key_path = key_path or []
# We can have the same conflict appear more times because we keep only
# one of the possible resolutions as a conflict while we apply the
# other as a fallback. Sometimes multiple fallback dict diffs
# conflict with a single change.
self.conflict_set = set()
self.skipped_lists = set()
self.merged_root = None
self.list_backups = {}
def _build_skipped_lists(self):
lists = set()
lists.update(_get_list_fields(self.head, []))
lists.intersection_update(_get_list_fields(self.update, []))
for l in lists:
dotted = get_dotted_key_path(l, True)
if dotted not in self.data_lists:
self.skipped_lists.add(l)
def _backup_lists(self):
self._build_skipped_lists()
for l in self.skipped_lists:
self.list_backups[l] = (
get_obj_at_key_path(self.root, l),
get_obj_at_key_path(self.head, l),
get_obj_at_key_path(self.update, l))
# The root is the only one that may not be there. Head and update
# are retrieved using list intersection.
del_obj_at_key_path(self.root, l, False)
del_obj_at_key_path(self.head, l)
del_obj_at_key_path(self.update, l)
def _restore_lists(self):
for l, (bak_r, bak_h, bak_u) in six.iteritems(self.list_backups):
if bak_r is not None:
set_obj_at_key_path(self.root, l, bak_r)
set_obj_at_key_path(self.head, l, bak_h)
set_obj_at_key_path(self.update, l, bak_u)
@property
def conflicts(self):
"""List of conflicts for the current object."""
# Make this compatible with the project convention (list of conflicts).
return list(self.conflict_set)
def _merge_base_values(self):
if self.head == self.update:
self.merged_root = self.head
elif self.head == NOTHING:
self.merged_root = self.update
elif self.update == NOTHING:
self.merged_root = self.head
elif self.head == self.root:
self.merged_root = self.update
elif self.update == self.root:
self.merged_root = self.head
else:
strategy = self._get_rule_for_field(self.key_path)
self.merged_root, conflict = {
'f': (self.head, self.update),
's': (self.update, self.head)}[strategy]
self.conflict_set.add(
Conflict(ConflictType.SET_FIELD, (), conflict))
def _merge_dicts(self):
self._backup_lists()
non_list_merger = Merger(self.root, self.head, self.update, {})
try:
non_list_merger.run()
except UnresolvedConflictsException as e:
self._solve_dict_conflicts(non_list_merger, e.content)
self._restore_lists()
self.merged_root = patch(
dedupe_list(non_list_merger.unified_patches),
self.root
)
def _solve_dict_conflicts(self, non_list_merger, conflicts):
strategies = [self._get_custom_strategy(conflict)
for conflict in conflicts]
non_list_merger.continue_run(strategies)
for conflict, strategy in zip(conflicts, strategies):
conflict_patch = {'f': conflict.second_patch,
's': conflict.first_patch}[strategy]
self.conflict_set.update(patch_to_conflict_set(conflict_patch))
def _get_custom_strategy(self, patch):
full_path = self._get_path_from_patch(patch)
return self._get_rule_for_field(full_path)
@staticmethod
def _get_path_from_patch(patch):
_, field, modification = patch.first_patch
full_path = []
if isinstance(field, list):
full_path.extend(field)
elif field:
full_path.append(field)
if (isinstance(modification, list) and modification[0][0]):
full_path.append(modification[0][0])
return full_path
@staticmethod
def _operation_to_function(operation):
if callable(operation):
return operation
elif operation == DictMergerOps.FALLBACK_KEEP_HEAD:
return lambda head, update, down_path: 'f'
elif operation == DictMergerOps.FALLBACK_KEEP_UPDATE:
return lambda head, update, down_path: 's'
else:
return lambda head, update, down_path: None
def _absolute_path(self, field_path):
full_path = list(self.key_path) + field_path
return get_dotted_key_path(full_path, filter_int_keys=True)
def _get_rule_for_field(self, field_path):
current_path = self._absolute_path(field_path)
head = get_obj_at_key_path(self.head, field_path)
update = get_obj_at_key_path(self.update, field_path)
down_path = []
rule = None
while current_path:
operation = self._operation_to_function(
self.custom_ops.get(current_path)
)
rule = operation(head, update, down_path)
if rule:
break
current_path_parts = current_path.split('.')
current_path = '.'.join(current_path_parts[:-1])
down_path.append(current_path_parts[-1])
return rule or self.default_op(head, update, field_path)
|
inveniosoftware-contrib/json-merger
|
json_merger/contrib/inspirehep/match.py
|
distance_function_match
|
python
|
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]):
common = []
# We will keep track of the global index in the source list as we
# will successively reduce their sizes.
l1 = list(enumerate(l1))
l2 = list(enumerate(l2))
# Use the distance function and threshold on hints given by normalization.
# See _match_by_norm_func for implementation details.
# Also wrap the list element function function to ignore the global list
# index computed above.
for norm_fn in norm_funcs:
new_common, l1, l2 = _match_by_norm_func(
l1, l2,
lambda a: norm_fn(a[1]),
lambda a1, a2: dist_fn(a1[1], a2[1]),
thresh)
# Keep only the global list index in the end result.
common.extend((c1[0], c2[0]) for c1, c2 in new_common)
# Take any remaining umatched entries and try to match them using the
# Munkres algorithm.
dist_matrix = [[dist_fn(e1, e2) for i2, e2 in l2] for i1, e1 in l1]
# Call Munkres on connected components on the remaining bipartite graph.
# An edge links an element from l1 with an element from l2 only if
# the distance between the elements is less (or equal) than the theshold.
components = BipartiteConnectedComponents()
for l1_i in range(len(l1)):
for l2_i in range(len(l2)):
if dist_matrix[l1_i][l2_i] > thresh:
continue
components.add_edge(l1_i, l2_i)
for l1_indices, l2_indices in components.get_connected_components():
# Build a partial distance matrix for each connected component.
part_l1 = [l1[i] for i in l1_indices]
part_l2 = [l2[i] for i in l2_indices]
part_dist_matrix = [[dist_matrix[l1_i][l2_i] for l2_i in l2_indices]
for l1_i in l1_indices]
part_cmn = _match_munkres(part_l1, part_l2, part_dist_matrix, thresh)
common.extend((c1[0], c2[0]) for c1, c2 in part_cmn)
return common
|
Returns pairs of matching indices from l1 and l2.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L30-L76
|
[
"def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh):\n \"\"\"Matches elements in l1 and l2 using normalization functions.\n\n Splits the elements in each list into buckets given by the normalization\n function. If the same normalization value points to a bucket from the\n first list and a bucket from the second list, both with a single element\n we consider the elements in the list as matching if the distance between\n them is less (or equal) than the threshold.\n\n e.g. l1 = ['X1', 'Y1', 'Y2', 'Z5'], l2 = ['X1', 'Y3', 'Z1']\n norm_fn = lambda x: x[0]\n dist_fn = lambda e1, e2: 0 if e1 == e2 else 1\n thresh = 0\n\n The buckets will then be:\n l1_bucket = {'X': ['X1'], 'Y': ['Y1', 'Y2'], 'Z': ['Z5']}\n l2_bucket = {'X': ['X1'], 'Y': ['Y3'], 'Z': ['Z1']}\n\n For each normalized value:\n 'X' -> consider 'X1' equal with 'X1' since the distance is equal with\n the thershold\n 'Y' -> skip the lists since we have multiple possible matches\n 'Z' -> consider 'Z1' and 'Z5' as different since the distance is\n greater than the threshold.\n Return:\n [('X1', 'X2')]\n \"\"\"\n common = []\n\n l1_only_idx = set(range(len(l1)))\n l2_only_idx = set(range(len(l2)))\n\n buckets_l1 = _group_by_fn(enumerate(l1), lambda x: norm_fn(x[1]))\n buckets_l2 = _group_by_fn(enumerate(l2), lambda x: norm_fn(x[1]))\n\n for normed, l1_elements in buckets_l1.items():\n l2_elements = buckets_l2.get(normed, [])\n if not l1_elements or not l2_elements:\n continue\n _, (_, e1_first) = l1_elements[0]\n _, (_, e2_first) = l2_elements[0]\n match_is_ambiguous = not (\n len(l1_elements) == len(l2_elements) and (\n all(e2 == e2_first for (_, (_, e2)) in l2_elements) or\n all(e1 == e1_first for (_, (_, e1)) in l1_elements)\n )\n )\n if match_is_ambiguous:\n continue\n for (e1_idx, e1), (e2_idx, e2) in zip(l1_elements, l2_elements):\n if dist_fn(e1, e2) > thresh:\n continue\n l1_only_idx.remove(e1_idx)\n l2_only_idx.remove(e2_idx)\n common.append((e1, e2))\n\n l1_only = [l1[i] for i in l1_only_idx]\n l2_only = [l2[i] for i in l2_only_idx]\n\n return common, l1_only, l2_only\n",
"def _match_munkres(l1, l2, dist_matrix, thresh):\n \"\"\"Matches two lists using the Munkres algorithm.\n\n Returns pairs of matching indices from the two lists by minimizing the sum\n of the distance between the linked elements and taking only the elements\n which have the distance between them less (or equal) than the threshold.\n \"\"\"\n equal_dist_matches = set()\n m = Munkres()\n indices = m.compute(dist_matrix)\n\n for l1_idx, l2_idx in indices:\n dst = dist_matrix[l1_idx][l2_idx]\n if dst > thresh:\n continue\n for eq_l2_idx, eq_val in enumerate(dist_matrix[l1_idx]):\n if abs(dst - eq_val) < 1e-9:\n equal_dist_matches.add((l1_idx, eq_l2_idx))\n for eq_l1_idx, eq_row in enumerate(dist_matrix):\n if abs(dst - eq_row[l2_idx]) < 1e-9:\n equal_dist_matches.add((eq_l1_idx, l2_idx))\n\n return [(l1[l1_idx], l2[l2_idx]) for l1_idx, l2_idx in equal_dist_matches]\n",
"def add_edge(self, p1_node, p2_node):\n node_1 = (p1_node, None)\n node_2 = (None, p2_node)\n self._union(node_1, node_2)\n",
"def get_connected_components(self):\n components_by_root = _group_by_fn(self.parents.keys(),\n self._find)\n for root in components_by_root:\n components_by_root[root].append(root)\n\n for component in components_by_root.values():\n p1_nodes = []\n p2_nodes = []\n for p1_node, p2_node in component:\n if p1_node is None:\n p2_nodes.append(p2_node)\n if p2_node is None:\n p1_nodes.append(p1_node)\n yield (p1_nodes, p2_nodes)\n"
] |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
from munkres import Munkres
def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh):
"""Matches elements in l1 and l2 using normalization functions.
Splits the elements in each list into buckets given by the normalization
function. If the same normalization value points to a bucket from the
first list and a bucket from the second list, both with a single element
we consider the elements in the list as matching if the distance between
them is less (or equal) than the threshold.
e.g. l1 = ['X1', 'Y1', 'Y2', 'Z5'], l2 = ['X1', 'Y3', 'Z1']
norm_fn = lambda x: x[0]
dist_fn = lambda e1, e2: 0 if e1 == e2 else 1
thresh = 0
The buckets will then be:
l1_bucket = {'X': ['X1'], 'Y': ['Y1', 'Y2'], 'Z': ['Z5']}
l2_bucket = {'X': ['X1'], 'Y': ['Y3'], 'Z': ['Z1']}
For each normalized value:
'X' -> consider 'X1' equal with 'X1' since the distance is equal with
the thershold
'Y' -> skip the lists since we have multiple possible matches
'Z' -> consider 'Z1' and 'Z5' as different since the distance is
greater than the threshold.
Return:
[('X1', 'X2')]
"""
common = []
l1_only_idx = set(range(len(l1)))
l2_only_idx = set(range(len(l2)))
buckets_l1 = _group_by_fn(enumerate(l1), lambda x: norm_fn(x[1]))
buckets_l2 = _group_by_fn(enumerate(l2), lambda x: norm_fn(x[1]))
for normed, l1_elements in buckets_l1.items():
l2_elements = buckets_l2.get(normed, [])
if not l1_elements or not l2_elements:
continue
_, (_, e1_first) = l1_elements[0]
_, (_, e2_first) = l2_elements[0]
match_is_ambiguous = not (
len(l1_elements) == len(l2_elements) and (
all(e2 == e2_first for (_, (_, e2)) in l2_elements) or
all(e1 == e1_first for (_, (_, e1)) in l1_elements)
)
)
if match_is_ambiguous:
continue
for (e1_idx, e1), (e2_idx, e2) in zip(l1_elements, l2_elements):
if dist_fn(e1, e2) > thresh:
continue
l1_only_idx.remove(e1_idx)
l2_only_idx.remove(e2_idx)
common.append((e1, e2))
l1_only = [l1[i] for i in l1_only_idx]
l2_only = [l2[i] for i in l2_only_idx]
return common, l1_only, l2_only
def _match_munkres(l1, l2, dist_matrix, thresh):
"""Matches two lists using the Munkres algorithm.
Returns pairs of matching indices from the two lists by minimizing the sum
of the distance between the linked elements and taking only the elements
which have the distance between them less (or equal) than the threshold.
"""
equal_dist_matches = set()
m = Munkres()
indices = m.compute(dist_matrix)
for l1_idx, l2_idx in indices:
dst = dist_matrix[l1_idx][l2_idx]
if dst > thresh:
continue
for eq_l2_idx, eq_val in enumerate(dist_matrix[l1_idx]):
if abs(dst - eq_val) < 1e-9:
equal_dist_matches.add((l1_idx, eq_l2_idx))
for eq_l1_idx, eq_row in enumerate(dist_matrix):
if abs(dst - eq_row[l2_idx]) < 1e-9:
equal_dist_matches.add((eq_l1_idx, l2_idx))
return [(l1[l1_idx], l2[l2_idx]) for l1_idx, l2_idx in equal_dist_matches]
class BipartiteConnectedComponents(object):
"""Union-Find implementation for getting connected components."""
def __init__(self):
self.parents = {}
def add_edge(self, p1_node, p2_node):
node_1 = (p1_node, None)
node_2 = (None, p2_node)
self._union(node_1, node_2)
def get_connected_components(self):
components_by_root = _group_by_fn(self.parents.keys(),
self._find)
for root in components_by_root:
components_by_root[root].append(root)
for component in components_by_root.values():
p1_nodes = []
p2_nodes = []
for p1_node, p2_node in component:
if p1_node is None:
p2_nodes.append(p2_node)
if p2_node is None:
p1_nodes.append(p1_node)
yield (p1_nodes, p2_nodes)
def _union(self, node_1, node_2):
parent_1 = self._find(node_1)
parent_2 = self._find(node_2)
if parent_1 != parent_2:
self.parents[parent_1] = parent_2
def _find(self, node):
root = node
while root in self.parents:
root = self.parents[root]
while node in self.parents:
prev_node = node
node = self.parents[node]
self.parents[prev_node] = root
return root
def _group_by_fn(iterable, fn):
buckets = {}
for elem in iterable:
key = fn(elem)
if key not in buckets:
buckets[key] = []
buckets[key].append(elem)
return buckets
|
inveniosoftware-contrib/json-merger
|
json_merger/contrib/inspirehep/match.py
|
_match_by_norm_func
|
python
|
def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh):
common = []
l1_only_idx = set(range(len(l1)))
l2_only_idx = set(range(len(l2)))
buckets_l1 = _group_by_fn(enumerate(l1), lambda x: norm_fn(x[1]))
buckets_l2 = _group_by_fn(enumerate(l2), lambda x: norm_fn(x[1]))
for normed, l1_elements in buckets_l1.items():
l2_elements = buckets_l2.get(normed, [])
if not l1_elements or not l2_elements:
continue
_, (_, e1_first) = l1_elements[0]
_, (_, e2_first) = l2_elements[0]
match_is_ambiguous = not (
len(l1_elements) == len(l2_elements) and (
all(e2 == e2_first for (_, (_, e2)) in l2_elements) or
all(e1 == e1_first for (_, (_, e1)) in l1_elements)
)
)
if match_is_ambiguous:
continue
for (e1_idx, e1), (e2_idx, e2) in zip(l1_elements, l2_elements):
if dist_fn(e1, e2) > thresh:
continue
l1_only_idx.remove(e1_idx)
l2_only_idx.remove(e2_idx)
common.append((e1, e2))
l1_only = [l1[i] for i in l1_only_idx]
l2_only = [l2[i] for i in l2_only_idx]
return common, l1_only, l2_only
|
Matches elements in l1 and l2 using normalization functions.
Splits the elements in each list into buckets given by the normalization
function. If the same normalization value points to a bucket from the
first list and a bucket from the second list, both with a single element
we consider the elements in the list as matching if the distance between
them is less (or equal) than the threshold.
e.g. l1 = ['X1', 'Y1', 'Y2', 'Z5'], l2 = ['X1', 'Y3', 'Z1']
norm_fn = lambda x: x[0]
dist_fn = lambda e1, e2: 0 if e1 == e2 else 1
thresh = 0
The buckets will then be:
l1_bucket = {'X': ['X1'], 'Y': ['Y1', 'Y2'], 'Z': ['Z5']}
l2_bucket = {'X': ['X1'], 'Y': ['Y3'], 'Z': ['Z1']}
For each normalized value:
'X' -> consider 'X1' equal with 'X1' since the distance is equal with
the thershold
'Y' -> skip the lists since we have multiple possible matches
'Z' -> consider 'Z1' and 'Z5' as different since the distance is
greater than the threshold.
Return:
[('X1', 'X2')]
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L79-L138
|
[
"def _group_by_fn(iterable, fn):\n buckets = {}\n for elem in iterable:\n key = fn(elem)\n if key not in buckets:\n buckets[key] = []\n buckets[key].append(elem)\n return buckets\n"
] |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
from munkres import Munkres
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]):
"""Returns pairs of matching indices from l1 and l2."""
common = []
# We will keep track of the global index in the source list as we
# will successively reduce their sizes.
l1 = list(enumerate(l1))
l2 = list(enumerate(l2))
# Use the distance function and threshold on hints given by normalization.
# See _match_by_norm_func for implementation details.
# Also wrap the list element function function to ignore the global list
# index computed above.
for norm_fn in norm_funcs:
new_common, l1, l2 = _match_by_norm_func(
l1, l2,
lambda a: norm_fn(a[1]),
lambda a1, a2: dist_fn(a1[1], a2[1]),
thresh)
# Keep only the global list index in the end result.
common.extend((c1[0], c2[0]) for c1, c2 in new_common)
# Take any remaining umatched entries and try to match them using the
# Munkres algorithm.
dist_matrix = [[dist_fn(e1, e2) for i2, e2 in l2] for i1, e1 in l1]
# Call Munkres on connected components on the remaining bipartite graph.
# An edge links an element from l1 with an element from l2 only if
# the distance between the elements is less (or equal) than the theshold.
components = BipartiteConnectedComponents()
for l1_i in range(len(l1)):
for l2_i in range(len(l2)):
if dist_matrix[l1_i][l2_i] > thresh:
continue
components.add_edge(l1_i, l2_i)
for l1_indices, l2_indices in components.get_connected_components():
# Build a partial distance matrix for each connected component.
part_l1 = [l1[i] for i in l1_indices]
part_l2 = [l2[i] for i in l2_indices]
part_dist_matrix = [[dist_matrix[l1_i][l2_i] for l2_i in l2_indices]
for l1_i in l1_indices]
part_cmn = _match_munkres(part_l1, part_l2, part_dist_matrix, thresh)
common.extend((c1[0], c2[0]) for c1, c2 in part_cmn)
return common
def _match_munkres(l1, l2, dist_matrix, thresh):
"""Matches two lists using the Munkres algorithm.
Returns pairs of matching indices from the two lists by minimizing the sum
of the distance between the linked elements and taking only the elements
which have the distance between them less (or equal) than the threshold.
"""
equal_dist_matches = set()
m = Munkres()
indices = m.compute(dist_matrix)
for l1_idx, l2_idx in indices:
dst = dist_matrix[l1_idx][l2_idx]
if dst > thresh:
continue
for eq_l2_idx, eq_val in enumerate(dist_matrix[l1_idx]):
if abs(dst - eq_val) < 1e-9:
equal_dist_matches.add((l1_idx, eq_l2_idx))
for eq_l1_idx, eq_row in enumerate(dist_matrix):
if abs(dst - eq_row[l2_idx]) < 1e-9:
equal_dist_matches.add((eq_l1_idx, l2_idx))
return [(l1[l1_idx], l2[l2_idx]) for l1_idx, l2_idx in equal_dist_matches]
class BipartiteConnectedComponents(object):
"""Union-Find implementation for getting connected components."""
def __init__(self):
self.parents = {}
def add_edge(self, p1_node, p2_node):
node_1 = (p1_node, None)
node_2 = (None, p2_node)
self._union(node_1, node_2)
def get_connected_components(self):
components_by_root = _group_by_fn(self.parents.keys(),
self._find)
for root in components_by_root:
components_by_root[root].append(root)
for component in components_by_root.values():
p1_nodes = []
p2_nodes = []
for p1_node, p2_node in component:
if p1_node is None:
p2_nodes.append(p2_node)
if p2_node is None:
p1_nodes.append(p1_node)
yield (p1_nodes, p2_nodes)
def _union(self, node_1, node_2):
parent_1 = self._find(node_1)
parent_2 = self._find(node_2)
if parent_1 != parent_2:
self.parents[parent_1] = parent_2
def _find(self, node):
root = node
while root in self.parents:
root = self.parents[root]
while node in self.parents:
prev_node = node
node = self.parents[node]
self.parents[prev_node] = root
return root
def _group_by_fn(iterable, fn):
buckets = {}
for elem in iterable:
key = fn(elem)
if key not in buckets:
buckets[key] = []
buckets[key].append(elem)
return buckets
|
inveniosoftware-contrib/json-merger
|
json_merger/contrib/inspirehep/match.py
|
_match_munkres
|
python
|
def _match_munkres(l1, l2, dist_matrix, thresh):
equal_dist_matches = set()
m = Munkres()
indices = m.compute(dist_matrix)
for l1_idx, l2_idx in indices:
dst = dist_matrix[l1_idx][l2_idx]
if dst > thresh:
continue
for eq_l2_idx, eq_val in enumerate(dist_matrix[l1_idx]):
if abs(dst - eq_val) < 1e-9:
equal_dist_matches.add((l1_idx, eq_l2_idx))
for eq_l1_idx, eq_row in enumerate(dist_matrix):
if abs(dst - eq_row[l2_idx]) < 1e-9:
equal_dist_matches.add((eq_l1_idx, l2_idx))
return [(l1[l1_idx], l2[l2_idx]) for l1_idx, l2_idx in equal_dist_matches]
|
Matches two lists using the Munkres algorithm.
Returns pairs of matching indices from the two lists by minimizing the sum
of the distance between the linked elements and taking only the elements
which have the distance between them less (or equal) than the threshold.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L141-L163
| null |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
from munkres import Munkres
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]):
"""Returns pairs of matching indices from l1 and l2."""
common = []
# We will keep track of the global index in the source list as we
# will successively reduce their sizes.
l1 = list(enumerate(l1))
l2 = list(enumerate(l2))
# Use the distance function and threshold on hints given by normalization.
# See _match_by_norm_func for implementation details.
# Also wrap the list element function function to ignore the global list
# index computed above.
for norm_fn in norm_funcs:
new_common, l1, l2 = _match_by_norm_func(
l1, l2,
lambda a: norm_fn(a[1]),
lambda a1, a2: dist_fn(a1[1], a2[1]),
thresh)
# Keep only the global list index in the end result.
common.extend((c1[0], c2[0]) for c1, c2 in new_common)
# Take any remaining umatched entries and try to match them using the
# Munkres algorithm.
dist_matrix = [[dist_fn(e1, e2) for i2, e2 in l2] for i1, e1 in l1]
# Call Munkres on connected components on the remaining bipartite graph.
# An edge links an element from l1 with an element from l2 only if
# the distance between the elements is less (or equal) than the theshold.
components = BipartiteConnectedComponents()
for l1_i in range(len(l1)):
for l2_i in range(len(l2)):
if dist_matrix[l1_i][l2_i] > thresh:
continue
components.add_edge(l1_i, l2_i)
for l1_indices, l2_indices in components.get_connected_components():
# Build a partial distance matrix for each connected component.
part_l1 = [l1[i] for i in l1_indices]
part_l2 = [l2[i] for i in l2_indices]
part_dist_matrix = [[dist_matrix[l1_i][l2_i] for l2_i in l2_indices]
for l1_i in l1_indices]
part_cmn = _match_munkres(part_l1, part_l2, part_dist_matrix, thresh)
common.extend((c1[0], c2[0]) for c1, c2 in part_cmn)
return common
def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh):
"""Matches elements in l1 and l2 using normalization functions.
Splits the elements in each list into buckets given by the normalization
function. If the same normalization value points to a bucket from the
first list and a bucket from the second list, both with a single element
we consider the elements in the list as matching if the distance between
them is less (or equal) than the threshold.
e.g. l1 = ['X1', 'Y1', 'Y2', 'Z5'], l2 = ['X1', 'Y3', 'Z1']
norm_fn = lambda x: x[0]
dist_fn = lambda e1, e2: 0 if e1 == e2 else 1
thresh = 0
The buckets will then be:
l1_bucket = {'X': ['X1'], 'Y': ['Y1', 'Y2'], 'Z': ['Z5']}
l2_bucket = {'X': ['X1'], 'Y': ['Y3'], 'Z': ['Z1']}
For each normalized value:
'X' -> consider 'X1' equal with 'X1' since the distance is equal with
the thershold
'Y' -> skip the lists since we have multiple possible matches
'Z' -> consider 'Z1' and 'Z5' as different since the distance is
greater than the threshold.
Return:
[('X1', 'X2')]
"""
common = []
l1_only_idx = set(range(len(l1)))
l2_only_idx = set(range(len(l2)))
buckets_l1 = _group_by_fn(enumerate(l1), lambda x: norm_fn(x[1]))
buckets_l2 = _group_by_fn(enumerate(l2), lambda x: norm_fn(x[1]))
for normed, l1_elements in buckets_l1.items():
l2_elements = buckets_l2.get(normed, [])
if not l1_elements or not l2_elements:
continue
_, (_, e1_first) = l1_elements[0]
_, (_, e2_first) = l2_elements[0]
match_is_ambiguous = not (
len(l1_elements) == len(l2_elements) and (
all(e2 == e2_first for (_, (_, e2)) in l2_elements) or
all(e1 == e1_first for (_, (_, e1)) in l1_elements)
)
)
if match_is_ambiguous:
continue
for (e1_idx, e1), (e2_idx, e2) in zip(l1_elements, l2_elements):
if dist_fn(e1, e2) > thresh:
continue
l1_only_idx.remove(e1_idx)
l2_only_idx.remove(e2_idx)
common.append((e1, e2))
l1_only = [l1[i] for i in l1_only_idx]
l2_only = [l2[i] for i in l2_only_idx]
return common, l1_only, l2_only
class BipartiteConnectedComponents(object):
"""Union-Find implementation for getting connected components."""
def __init__(self):
self.parents = {}
def add_edge(self, p1_node, p2_node):
node_1 = (p1_node, None)
node_2 = (None, p2_node)
self._union(node_1, node_2)
def get_connected_components(self):
components_by_root = _group_by_fn(self.parents.keys(),
self._find)
for root in components_by_root:
components_by_root[root].append(root)
for component in components_by_root.values():
p1_nodes = []
p2_nodes = []
for p1_node, p2_node in component:
if p1_node is None:
p2_nodes.append(p2_node)
if p2_node is None:
p1_nodes.append(p1_node)
yield (p1_nodes, p2_nodes)
def _union(self, node_1, node_2):
parent_1 = self._find(node_1)
parent_2 = self._find(node_2)
if parent_1 != parent_2:
self.parents[parent_1] = parent_2
def _find(self, node):
root = node
while root in self.parents:
root = self.parents[root]
while node in self.parents:
prev_node = node
node = self.parents[node]
self.parents[prev_node] = root
return root
def _group_by_fn(iterable, fn):
buckets = {}
for elem in iterable:
key = fn(elem)
if key not in buckets:
buckets[key] = []
buckets[key].append(elem)
return buckets
|
inveniosoftware-contrib/json-merger
|
json_merger/conflict.py
|
Conflict.with_prefix
|
python
|
def with_prefix(self, root_path):
return Conflict(self.conflict_type, root_path + self.path, self.body)
|
Returns a new conflict with a prepended prefix as a path.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/conflict.py#L95-L97
| null |
class Conflict(tuple):
"""Immutable and Hashable representation of a conflict.
Attributes:
conflict_type: A :class:`json_merger.conflict.ConflictType` member.
path: A tuple containing the path to the conflictual field.
body: Optional value representing the body of the conflict.
Note:
Even if the conflict body can be any arbitrary object, this is saved
internally as an immutable object so that a Conflict instance can be
safely used in sets or as a dict key.
"""
# Based on http://stackoverflow.com/a/4828108
# Compatible with Python<=2.6
def __new__(cls, conflict_type, path, body):
if conflict_type not in _CONFLICTS:
raise ValueError('Bad Conflict Type %s' % conflict_type)
body = freeze(body)
return tuple.__new__(cls, (conflict_type, path, body))
conflict_type = property(lambda self: self[0])
path = property(lambda self: self[1])
body = property(lambda self: thaw(self[2]))
def to_json(self):
"""Deserializes conflict to a JSON object.
It returns list of:
`json-patch <https://tools.ietf.org/html/rfc6902>`_ format.
- REORDER, SET_FIELD become "op": "replace"
- MANUAL_MERGE, ADD_BACK_TO_HEAD become "op": "add"
- Path becomes `json-pointer <https://tools.ietf.org/html/rfc6901>`_
- Original conflict type is added to "$type"
"""
# map ConflictType to json-patch operator
path = self.path
if self.conflict_type in ('REORDER', 'SET_FIELD'):
op = 'replace'
elif self.conflict_type in ('MANUAL_MERGE', 'ADD_BACK_TO_HEAD'):
op = 'add'
path += ('-',)
elif self.conflict_type == 'REMOVE_FIELD':
op = 'remove'
else:
raise ValueError(
'Conflict Type %s can not be mapped to a json-patch operation'
% conflict_type
)
# stringify path array
json_pointer = '/' + '/'.join(str(el) for el in path)
conflict_values = force_list(self.body)
conflicts = []
for value in conflict_values:
if value is not None or self.conflict_type == 'REMOVE_FIELD':
conflicts.append({
'path': json_pointer,
'op': op,
'value': value,
'$type': self.conflict_type
})
return json.dumps(conflicts)
|
inveniosoftware-contrib/json-merger
|
json_merger/conflict.py
|
Conflict.to_json
|
python
|
def to_json(self):
# map ConflictType to json-patch operator
path = self.path
if self.conflict_type in ('REORDER', 'SET_FIELD'):
op = 'replace'
elif self.conflict_type in ('MANUAL_MERGE', 'ADD_BACK_TO_HEAD'):
op = 'add'
path += ('-',)
elif self.conflict_type == 'REMOVE_FIELD':
op = 'remove'
else:
raise ValueError(
'Conflict Type %s can not be mapped to a json-patch operation'
% conflict_type
)
# stringify path array
json_pointer = '/' + '/'.join(str(el) for el in path)
conflict_values = force_list(self.body)
conflicts = []
for value in conflict_values:
if value is not None or self.conflict_type == 'REMOVE_FIELD':
conflicts.append({
'path': json_pointer,
'op': op,
'value': value,
'$type': self.conflict_type
})
return json.dumps(conflicts)
|
Deserializes conflict to a JSON object.
It returns list of:
`json-patch <https://tools.ietf.org/html/rfc6902>`_ format.
- REORDER, SET_FIELD become "op": "replace"
- MANUAL_MERGE, ADD_BACK_TO_HEAD become "op": "add"
- Path becomes `json-pointer <https://tools.ietf.org/html/rfc6901>`_
- Original conflict type is added to "$type"
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/conflict.py#L99-L139
|
[
"def force_list(data):\n if not isinstance(data, (list, tuple, set)):\n return [data]\n elif isinstance(data, (tuple, set)):\n return list(data)\n return data\n"
] |
class Conflict(tuple):
"""Immutable and Hashable representation of a conflict.
Attributes:
conflict_type: A :class:`json_merger.conflict.ConflictType` member.
path: A tuple containing the path to the conflictual field.
body: Optional value representing the body of the conflict.
Note:
Even if the conflict body can be any arbitrary object, this is saved
internally as an immutable object so that a Conflict instance can be
safely used in sets or as a dict key.
"""
# Based on http://stackoverflow.com/a/4828108
# Compatible with Python<=2.6
def __new__(cls, conflict_type, path, body):
if conflict_type not in _CONFLICTS:
raise ValueError('Bad Conflict Type %s' % conflict_type)
body = freeze(body)
return tuple.__new__(cls, (conflict_type, path, body))
conflict_type = property(lambda self: self[0])
path = property(lambda self: self[1])
body = property(lambda self: thaw(self[2]))
def with_prefix(self, root_path):
"""Returns a new conflict with a prepended prefix as a path."""
return Conflict(self.conflict_type, root_path + self.path, self.body)
|
inveniosoftware-contrib/json-merger
|
json_merger/merger.py
|
Merger.merge
|
python
|
def merge(self):
self.merged_root = self._recursive_merge(self.root, self.head,
self.update)
if self.conflicts:
raise MergeError('Conflicts Occurred in Merge Process',
self.conflicts)
|
Populates result members.
Performs the merge algorithm using the specified config and fills in
the members that provide stats about the merging procedure.
Attributes:
merged_root: The result of the merge.
aligned_root, aligned_head, aligned_update: Copies of root, head
and update in which all matched list entities have the same
list index for easier diff viewing.
head_stats, update_stats: Stats for each list field present in the
head or update objects. Instance of
:class:`json_merger.stats.ListMatchStats`
conflicts: List of :class:`json_merger.conflict.Conflict` instances
that occured during the merge.
Raises:
:class:`json_merger.errors.MergeError` : If conflicts occur during
the call.
Example:
>>> from json_merger import Merger
>>> # We compare people by their name
>>> from json_merger.comparator import PrimaryKeyComparator
>>> from json_merger.config import DictMergerOps, UnifierOps
>>> from json_merger.errors import MergeError
>>> # Use this only for doctest :)
>>> from pprint import pprint as pp
>>>
>>> root = {'people': [{'name': 'Jimmy', 'age': 30}]}
>>> head = {'people': [{'name': 'Jimmy', 'age': 31},
... {'name': 'George'}]}
>>> update = {'people': [{'name': 'John'},
... {'name': 'Jimmy', 'age': 32}]}
>>>
>>> class NameComparator(PrimaryKeyComparator):
... # Two objects are the same entitity if they have the
... # same name.
... primary_key_fields = ['name']
>>> m = Merger(root, head, update,
... DictMergerOps.FALLBACK_KEEP_HEAD,
... UnifierOps.KEEP_UPDATE_AND_HEAD_ENTITIES_HEAD_FIRST,
... comparators = {'people': NameComparator})
>>> # We do a merge
>>> try:
... m.merge()
... except MergeError as e:
... # Conflicts are the same thing as the exception content.
... assert e.content == m.conflicts
>>> # This is how the lists are aligned:
>>> pp(m.aligned_root['people'], width=60)
['#$PLACEHOLDER$#',
{'age': 30, 'name': 'Jimmy'},
'#$PLACEHOLDER$#']
>>> pp(m.aligned_head['people'], width=60)
['#$PLACEHOLDER$#',
{'age': 31, 'name': 'Jimmy'},
{'name': 'George'}]
>>> pp(m.aligned_update['people'], width=60)
[{'name': 'John'},
{'age': 32, 'name': 'Jimmy'},
'#$PLACEHOLDER$#']
>>> # This is the end result of the merge:
>>> pp(m.merged_root, width=60)
{'people': [{'name': 'John'},
{'age': 31, 'name': 'Jimmy'},
{'name': 'George'}]}
>>> # With some conflicts:
>>> pp(m.conflicts, width=60)
[('SET_FIELD', ('people', 1, 'age'), 32)]
>>> # And some stats:
>>> pp(m.head_stats[('people',)].in_result)
[{'age': 31, 'name': 'Jimmy'}, {'name': 'George'}]
>>> pp(m.update_stats[('people',)].not_in_result)
[]
Note:
Even if conflicts occur, merged_root, aligned_root, aligned_head
and aligned_update are always populated by following the
startegies set for the merger instance.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/merger.py#L135-L224
|
[
"def _recursive_merge(self, root, head, update, key_path=()):\n dotted_key_path = get_dotted_key_path(key_path, filter_int_keys=True)\n\n if (isinstance(head, list) and isinstance(update, list) and\n dotted_key_path not in self.data_lists):\n # In this case we are merging two lists of objects.\n lists_to_unify = [()]\n if not isinstance(root, list):\n root = []\n else:\n # Otherwise we merge everything but the lists using DictMergerOps.\n m = self._merge_objects(root, head, update, key_path)\n root = m.merged_root\n lists_to_unify = m.skipped_lists\n\n for list_field in lists_to_unify:\n absolute_key_path = key_path + list_field\n\n root_l = get_obj_at_key_path(root, list_field, [])\n head_l = get_obj_at_key_path(head, list_field, [])\n update_l = get_obj_at_key_path(update, list_field, [])\n\n unifier = self._unify_lists(root_l, head_l, update_l,\n absolute_key_path)\n\n new_list = []\n for idx, objects in enumerate(unifier.unified):\n root_obj, head_obj, update_obj = objects\n new_obj = self._recursive_merge(root_obj, head_obj, update_obj,\n absolute_key_path + (idx, ))\n new_list.append(new_obj)\n\n root = set_obj_at_key_path(root, list_field, new_list)\n self._build_aligned_lists_and_stats(unifier, absolute_key_path)\n\n return root\n"
] |
class Merger(object):
"""Class that merges two JSON objects that share a common ancestor.
This class treats by default all lists as being lists of entities and
offers support for matching their elements by their content, by specifing
per-field comparator classes.
"""
def __init__(self, root, head, update,
default_dict_merge_op, default_list_merge_op,
list_dict_ops=None, list_merge_ops=None,
comparators=None, data_lists=None):
"""
Args:
root: A common ancestor of the two objects being merged.
head: One of the objects that is being merged. Refers to the
version that is currently in use. (e.g. a displayed database
record)
update: The second object that is being merged. Refers to an update
that needs to be integrated with the in-use version.
default_dict_merge_op
(:class:`json_merger.config.DictMergerOps` class attribute):
Default strategy for merging regular non list JSON values
(strings, numbers, other objects).
default_list_merge_op
(:class:`json_merger.config.UnifierOps` class attribute):
Default strategy for merging two lists of entities.
dict_merge_ops: Defines custom strategies for merging dict of
entities.
Dict formatted as:
* keys -- a config string
* values -- a class attribute of
:class:`json_merger.config.DictMergerOps`
list_merge_ops: Defines custom strategies for merging lists of
entities.
Dict formatted as:
* keys -- a config string
* values -- a class attribute of
:class:`json_merger.config.UnifierOps`
comparators: Defines classes used for rendering entities in list
fields as equal.
Dict formatted as:
* keys -- a config string
* values -- a class that extends
:class:`json_merger.comparator.BaseComparator`
data_lists: List of config strings defining the lists that are not
treated as lists of entities.
Note:
A configuration string represents the path towards a list field in
the object sepparated with dots.
Example:
Configuration strings can be:
For ``{'lst': [{'id': 0, 'tags': ['foo', 'bar']}]}``:
* the config string for the top level list is ``'lst'``
* the config string for the tags lists is ``'lst.tags'``
"""
self.comparators = comparators or {}
self.data_lists = set(data_lists or [])
self.list_dict_ops = list_dict_ops or {}
self.list_merge_ops = list_merge_ops or {}
self.default_dict_merge_op = default_dict_merge_op
self.default_list_merge_op = default_list_merge_op
self.root = copy.deepcopy(root)
self.head = copy.deepcopy(head)
self.update = copy.deepcopy(update)
self.head_stats = {}
self.update_stats = {}
self.conflicts = []
self.merged_root = None
self.aligned_root = copy.deepcopy(root)
self.aligned_head = copy.deepcopy(head)
self.aligned_update = copy.deepcopy(update)
def _recursive_merge(self, root, head, update, key_path=()):
dotted_key_path = get_dotted_key_path(key_path, filter_int_keys=True)
if (isinstance(head, list) and isinstance(update, list) and
dotted_key_path not in self.data_lists):
# In this case we are merging two lists of objects.
lists_to_unify = [()]
if not isinstance(root, list):
root = []
else:
# Otherwise we merge everything but the lists using DictMergerOps.
m = self._merge_objects(root, head, update, key_path)
root = m.merged_root
lists_to_unify = m.skipped_lists
for list_field in lists_to_unify:
absolute_key_path = key_path + list_field
root_l = get_obj_at_key_path(root, list_field, [])
head_l = get_obj_at_key_path(head, list_field, [])
update_l = get_obj_at_key_path(update, list_field, [])
unifier = self._unify_lists(root_l, head_l, update_l,
absolute_key_path)
new_list = []
for idx, objects in enumerate(unifier.unified):
root_obj, head_obj, update_obj = objects
new_obj = self._recursive_merge(root_obj, head_obj, update_obj,
absolute_key_path + (idx, ))
new_list.append(new_obj)
root = set_obj_at_key_path(root, list_field, new_list)
self._build_aligned_lists_and_stats(unifier, absolute_key_path)
return root
def _merge_objects(self, root, head, update, key_path):
data_lists = get_conf_set_for_key_path(self.data_lists, key_path)
object_merger = SkipListsMerger(root, head, update,
self.default_dict_merge_op,
data_lists, self.list_dict_ops,
key_path)
try:
object_merger.merge()
except MergeError as e:
self.conflicts.extend(c.with_prefix(key_path) for c in e.content)
return object_merger
def _unify_lists(self, root, head, update, key_path):
dotted_key_path = get_dotted_key_path(key_path, True)
operation = self.list_merge_ops.get(dotted_key_path,
self.default_list_merge_op)
comparator_cls = self.comparators.get(dotted_key_path,
DefaultComparator)
list_unifier = ListUnifier(root, head, update,
operation, comparator_cls)
try:
list_unifier.unify()
except MergeError as e:
self.conflicts.extend(c.with_prefix(key_path) for c in e.content)
return list_unifier
def _build_aligned_lists_and_stats(self, list_unifier, key_path):
root_list = []
head_list = []
update_list = []
for root_obj, head_obj, update_obj in list_unifier.unified:
# Cast NOTHING objects to a placeholder so we reserialize back to
# JSON if needed.
root_list.append(root_obj or PLACEHOLDER_STR)
head_list.append(head_obj or PLACEHOLDER_STR)
update_list.append(update_obj or PLACEHOLDER_STR)
# Try to put back the list if the key path existed in the first place.
self.aligned_root = set_obj_at_key_path(self.aligned_root,
key_path, root_list, False)
self.aligned_head = set_obj_at_key_path(self.aligned_head,
key_path, head_list, False)
self.aligned_update = set_obj_at_key_path(self.aligned_update,
key_path, update_list, False)
# Also copy over the stats.
self.head_stats[key_path] = list_unifier.head_stats
self.update_stats[key_path] = list_unifier.update_stats
|
inveniosoftware-contrib/json-merger
|
json_merger/stats.py
|
ListMatchStats.move_to_result
|
python
|
def move_to_result(self, lst_idx):
self.in_result_idx.add(lst_idx)
if lst_idx in self.not_in_result_root_match_idx:
self.not_in_result_root_match_idx.remove(lst_idx)
|
Moves element from lst available at lst_idx.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/stats.py#L72-L77
| null |
class ListMatchStats(object):
"""Class for holding list entity matching stats."""
def __init__(self, lst, root):
"""
Args:
lst: The list of elements that needs to be matched.
root: The ancestor of the list of elements that needs to be
matched.
Attributes:
in_result_idx: Indices of elements in lst that are present in the
end result.
in_result: Elements in lst that are present in the end result.
not_in_result_idx: Indices of elements in lst that are not present
in the end result.
not_in_result: Elements in lst that are not present in the end
result.
not_in_result_root_match_idx: Indices of elements that are not in
the end result but were matched with root elements.
not_in_result_root_match: Elements that are not in the end result
but were matched with root elements.
not_in_result_not_root_match_idx: Indices of elements that are not
in the end result and were not matched with any root elements.
not_in_result_not_root_match: Elements that are not in the end
result and were not matched with any root elements.
not_in_result_root_match_pairs: Pairs of (lst, root) elements
that are not in the end result but were matched.
"""
self.lst = lst
self.root = root
self.in_result_idx = set()
self.not_in_result_root_match_idx = set()
self.root_matches = {}
def add_root_match(self, lst_idx, root_idx):
"""Adds a match for the elements avaialble at lst_idx and root_idx."""
self.root_matches[lst_idx] = root_idx
if lst_idx in self.in_result_idx:
return
self.not_in_result_root_match_idx.add(lst_idx)
@property
def not_in_result_idx(self):
return set(range(len(self.lst))).difference(self.in_result_idx)
@property
def not_in_result_not_root_match_idx(self):
return self.not_in_result_idx.difference(
self.not_in_result_root_match_idx)
@property
def in_result(self):
return [self.lst[e] for e in self.in_result_idx]
@property
def not_in_result(self):
return [self.lst[e] for e in self.not_in_result_idx]
@property
def not_in_result_root_match(self):
return [self.lst[e] for e in self.not_in_result_root_match_idx]
@property
def not_in_result_not_root_match(self):
return [self.lst[e] for e in self.not_in_result_not_root_match_idx]
@property
def not_in_result_root_match_pairs(self):
return [(self.lst[e], self.root[self.root_matches[e]])
for e in self.not_in_result_root_match_idx]
@property
def not_matched_root_objects(self):
matched_root_idx = set(self.root_matches.values())
return [o for idx, o in enumerate(self.root)
if idx not in matched_root_idx]
|
inveniosoftware-contrib/json-merger
|
json_merger/stats.py
|
ListMatchStats.add_root_match
|
python
|
def add_root_match(self, lst_idx, root_idx):
self.root_matches[lst_idx] = root_idx
if lst_idx in self.in_result_idx:
return
self.not_in_result_root_match_idx.add(lst_idx)
|
Adds a match for the elements avaialble at lst_idx and root_idx.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/stats.py#L79-L85
| null |
class ListMatchStats(object):
"""Class for holding list entity matching stats."""
def __init__(self, lst, root):
"""
Args:
lst: The list of elements that needs to be matched.
root: The ancestor of the list of elements that needs to be
matched.
Attributes:
in_result_idx: Indices of elements in lst that are present in the
end result.
in_result: Elements in lst that are present in the end result.
not_in_result_idx: Indices of elements in lst that are not present
in the end result.
not_in_result: Elements in lst that are not present in the end
result.
not_in_result_root_match_idx: Indices of elements that are not in
the end result but were matched with root elements.
not_in_result_root_match: Elements that are not in the end result
but were matched with root elements.
not_in_result_not_root_match_idx: Indices of elements that are not
in the end result and were not matched with any root elements.
not_in_result_not_root_match: Elements that are not in the end
result and were not matched with any root elements.
not_in_result_root_match_pairs: Pairs of (lst, root) elements
that are not in the end result but were matched.
"""
self.lst = lst
self.root = root
self.in_result_idx = set()
self.not_in_result_root_match_idx = set()
self.root_matches = {}
def move_to_result(self, lst_idx):
"""Moves element from lst available at lst_idx."""
self.in_result_idx.add(lst_idx)
if lst_idx in self.not_in_result_root_match_idx:
self.not_in_result_root_match_idx.remove(lst_idx)
@property
def not_in_result_idx(self):
return set(range(len(self.lst))).difference(self.in_result_idx)
@property
def not_in_result_not_root_match_idx(self):
return self.not_in_result_idx.difference(
self.not_in_result_root_match_idx)
@property
def in_result(self):
return [self.lst[e] for e in self.in_result_idx]
@property
def not_in_result(self):
return [self.lst[e] for e in self.not_in_result_idx]
@property
def not_in_result_root_match(self):
return [self.lst[e] for e in self.not_in_result_root_match_idx]
@property
def not_in_result_not_root_match(self):
return [self.lst[e] for e in self.not_in_result_not_root_match_idx]
@property
def not_in_result_root_match_pairs(self):
return [(self.lst[e], self.root[self.root_matches[e]])
for e in self.not_in_result_root_match_idx]
@property
def not_matched_root_objects(self):
matched_root_idx = set(self.root_matches.values())
return [o for idx, o in enumerate(self.root)
if idx not in matched_root_idx]
|
inveniosoftware-contrib/json-merger
|
json_merger/contrib/inspirehep/author_util.py
|
token_distance
|
python
|
def token_distance(t1, t2, initial_match_penalization):
if isinstance(t1, NameInitial) or isinstance(t2, NameInitial):
if t1.token == t2.token:
return 0
if t1 == t2:
return initial_match_penalization
return 1.0
return _normalized_edit_dist(t1.token, t2.token)
|
Calculates the edit distance between two tokens.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/author_util.py#L60-L68
| null |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
import re
import unicodedata
import editdistance
import six
from munkres import Munkres
from unidecode import unidecode
_RE_NAME_TOKEN_SEPARATOR = re.compile(r'[^\w\'-]+', re.UNICODE)
def _normalized_edit_dist(s1, s2):
return float(editdistance.eval(s1, s2)) / max(len(s1), len(s2), 1)
class NameToken(object):
def __init__(self, token):
self.token = token.lower()
def __eq__(self, other):
return self.token == other.token
def __repr__(self):
return repr(u'{}: {}'.format(self.__class__.__name__,
self.token))
class NameInitial(NameToken):
def __eq__(self, other):
return self.token == other.token[:len(self.token)]
def simple_tokenize(name):
"""Simple tokenizer function to be used with the normalizers."""
last_names, first_names = name.split(',')
last_names = _RE_NAME_TOKEN_SEPARATOR.split(last_names)
first_names = _RE_NAME_TOKEN_SEPARATOR.split(first_names)
first_names = [NameToken(n) if len(n) > 1 else NameInitial(n)
for n in first_names if n]
last_names = [NameToken(n) if len(n) > 1 else NameInitial(n)
for n in last_names if n]
return {'lastnames': last_names,
'nonlastnames': first_names}
class AuthorNameNormalizer(object):
"""Callable that normalizes an author name given a tokenizer function."""
def __init__(self, tokenize_function,
first_names_number=None,
first_name_to_initial=False,
asciify=False):
"""Initialize the normalizer.
Args:
tokenize_function:
A function that receives an author name and parses it out in
the following format:
{'lastnames': NameToken instance list,
'nonlastnames': NameToken instance list}
first_names_number:
Max number of first names too keep in the normalized name.
If None, keep all first names
first_name_to_initial:
If set to True, all first names will be transformed into
initials.
asciify:
If set to True, all non-ASCII characters will be replaced by
the closest ASCII character, e.g. 'é' -> 'e'.
"""
self.tokenize_function = tokenize_function
self.first_names_number = first_names_number
self.first_name_to_initial = first_name_to_initial
self.normalize_chars = lambda x: _asciify(x) if asciify else x
def __call__(self, author):
name = author.get('full_name', '')
name = _decode_if_not_unicode(name)
name = self.normalize_chars(name)
tokens = self.tokenize_function(name)
last_fn_char = 1 if self.first_name_to_initial else None
last_fn_idx = self.first_names_number
return (tuple(n.token.lower() for n in tokens['lastnames']) +
tuple(n.token.lower()[:last_fn_char]
for n in tokens['nonlastnames'][:last_fn_idx]))
class AuthorNameDistanceCalculator(object):
"""Callable that calculates a distance between two author's names."""
def __init__(self, tokenize_function, match_on_initial_penalization=0.05,
full_name_field='full_name'):
"""Initialize the distance calculator.
Args:
tokenize_function: A function that receives an author name and
parses it out in the following format:
{'lastnames': NameToken instance list,
'nonlastnames': NameToken instance list}
match_on_initial_penalization:
The cost value of a match between an initial and a full name
starting with the same letter.
name_field:
The field in which an author record keeps the full name.
Note:
The default match_on_initial_penalization had the best results
on a test suite based on production data.
"""
self.tokenize_function = tokenize_function
self.match_on_initial_penalization = match_on_initial_penalization
self.name_field = full_name_field
def __call__(self, author1, author2):
# Return 1.0 on missing features.
if self.name_field not in author1:
return 1.0
if self.name_field not in author2:
return 1.0
# Normalize to unicode
name_a1 = _asciify(_decode_if_not_unicode(author1[self.name_field]))
name_a2 = _asciify(_decode_if_not_unicode(author2[self.name_field]))
tokens_a1 = self.tokenize_function(name_a1)
tokens_a2 = self.tokenize_function(name_a2)
tokens_a1 = tokens_a1['lastnames'] + tokens_a1['nonlastnames']
tokens_a2 = tokens_a2['lastnames'] + tokens_a2['nonlastnames']
# Match all names by editdistance.
dist_matrix = [
[token_distance(t1, t2, self.match_on_initial_penalization)
for t2 in tokens_a2] for t1 in tokens_a1]
matcher = Munkres()
indices = matcher.compute(dist_matrix)
cost = 0.0
matched_only_initials = True
for idx_a1, idx_a2 in indices:
cost += dist_matrix[idx_a1][idx_a2]
if (not isinstance(tokens_a1[idx_a1], NameInitial) or
not isinstance(tokens_a2[idx_a2], NameInitial)):
matched_only_initials = False
# Johnny, D will not be equal with Donny, J
if matched_only_initials:
return 1.0
return cost / max(min(len(tokens_a1), len(tokens_a2)), 1.0)
def _decode_if_not_unicode(value):
to_return = value
if not isinstance(value, six.text_type):
to_return = value.decode('utf-8')
return to_return
def _asciify(value):
return six.text_type(unidecode(value))
|
inveniosoftware-contrib/json-merger
|
json_merger/contrib/inspirehep/author_util.py
|
simple_tokenize
|
python
|
def simple_tokenize(name):
last_names, first_names = name.split(',')
last_names = _RE_NAME_TOKEN_SEPARATOR.split(last_names)
first_names = _RE_NAME_TOKEN_SEPARATOR.split(first_names)
first_names = [NameToken(n) if len(n) > 1 else NameInitial(n)
for n in first_names if n]
last_names = [NameToken(n) if len(n) > 1 else NameInitial(n)
for n in last_names if n]
return {'lastnames': last_names,
'nonlastnames': first_names}
|
Simple tokenizer function to be used with the normalizers.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/author_util.py#L71-L82
| null |
# -*- coding: utf-8 -*-
#
# This file is part of Inspirehep.
# Copyright (C) 2016 CERN.
#
# Inspirehep is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Inspirehep is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Inspirehep; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
from __future__ import absolute_import, print_function
import re
import unicodedata
import editdistance
import six
from munkres import Munkres
from unidecode import unidecode
_RE_NAME_TOKEN_SEPARATOR = re.compile(r'[^\w\'-]+', re.UNICODE)
def _normalized_edit_dist(s1, s2):
return float(editdistance.eval(s1, s2)) / max(len(s1), len(s2), 1)
class NameToken(object):
def __init__(self, token):
self.token = token.lower()
def __eq__(self, other):
return self.token == other.token
def __repr__(self):
return repr(u'{}: {}'.format(self.__class__.__name__,
self.token))
class NameInitial(NameToken):
def __eq__(self, other):
return self.token == other.token[:len(self.token)]
def token_distance(t1, t2, initial_match_penalization):
"""Calculates the edit distance between two tokens."""
if isinstance(t1, NameInitial) or isinstance(t2, NameInitial):
if t1.token == t2.token:
return 0
if t1 == t2:
return initial_match_penalization
return 1.0
return _normalized_edit_dist(t1.token, t2.token)
class AuthorNameNormalizer(object):
"""Callable that normalizes an author name given a tokenizer function."""
def __init__(self, tokenize_function,
first_names_number=None,
first_name_to_initial=False,
asciify=False):
"""Initialize the normalizer.
Args:
tokenize_function:
A function that receives an author name and parses it out in
the following format:
{'lastnames': NameToken instance list,
'nonlastnames': NameToken instance list}
first_names_number:
Max number of first names too keep in the normalized name.
If None, keep all first names
first_name_to_initial:
If set to True, all first names will be transformed into
initials.
asciify:
If set to True, all non-ASCII characters will be replaced by
the closest ASCII character, e.g. 'é' -> 'e'.
"""
self.tokenize_function = tokenize_function
self.first_names_number = first_names_number
self.first_name_to_initial = first_name_to_initial
self.normalize_chars = lambda x: _asciify(x) if asciify else x
def __call__(self, author):
name = author.get('full_name', '')
name = _decode_if_not_unicode(name)
name = self.normalize_chars(name)
tokens = self.tokenize_function(name)
last_fn_char = 1 if self.first_name_to_initial else None
last_fn_idx = self.first_names_number
return (tuple(n.token.lower() for n in tokens['lastnames']) +
tuple(n.token.lower()[:last_fn_char]
for n in tokens['nonlastnames'][:last_fn_idx]))
class AuthorNameDistanceCalculator(object):
"""Callable that calculates a distance between two author's names."""
def __init__(self, tokenize_function, match_on_initial_penalization=0.05,
full_name_field='full_name'):
"""Initialize the distance calculator.
Args:
tokenize_function: A function that receives an author name and
parses it out in the following format:
{'lastnames': NameToken instance list,
'nonlastnames': NameToken instance list}
match_on_initial_penalization:
The cost value of a match between an initial and a full name
starting with the same letter.
name_field:
The field in which an author record keeps the full name.
Note:
The default match_on_initial_penalization had the best results
on a test suite based on production data.
"""
self.tokenize_function = tokenize_function
self.match_on_initial_penalization = match_on_initial_penalization
self.name_field = full_name_field
def __call__(self, author1, author2):
# Return 1.0 on missing features.
if self.name_field not in author1:
return 1.0
if self.name_field not in author2:
return 1.0
# Normalize to unicode
name_a1 = _asciify(_decode_if_not_unicode(author1[self.name_field]))
name_a2 = _asciify(_decode_if_not_unicode(author2[self.name_field]))
tokens_a1 = self.tokenize_function(name_a1)
tokens_a2 = self.tokenize_function(name_a2)
tokens_a1 = tokens_a1['lastnames'] + tokens_a1['nonlastnames']
tokens_a2 = tokens_a2['lastnames'] + tokens_a2['nonlastnames']
# Match all names by editdistance.
dist_matrix = [
[token_distance(t1, t2, self.match_on_initial_penalization)
for t2 in tokens_a2] for t1 in tokens_a1]
matcher = Munkres()
indices = matcher.compute(dist_matrix)
cost = 0.0
matched_only_initials = True
for idx_a1, idx_a2 in indices:
cost += dist_matrix[idx_a1][idx_a2]
if (not isinstance(tokens_a1[idx_a1], NameInitial) or
not isinstance(tokens_a2[idx_a2], NameInitial)):
matched_only_initials = False
# Johnny, D will not be equal with Donny, J
if matched_only_initials:
return 1.0
return cost / max(min(len(tokens_a1), len(tokens_a2)), 1.0)
def _decode_if_not_unicode(value):
to_return = value
if not isinstance(value, six.text_type):
to_return = value.decode('utf-8')
return to_return
def _asciify(value):
return six.text_type(unidecode(value))
|
inveniosoftware-contrib/json-merger
|
json_merger/comparator.py
|
BaseComparator.process_lists
|
python
|
def process_lists(self):
for l1_idx, obj1 in enumerate(self.l1):
for l2_idx, obj2 in enumerate(self.l2):
if self.equal(obj1, obj2):
self.matches.add((l1_idx, l2_idx))
|
Do any preprocessing of the lists.
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L45-L50
|
[
"def equal(self, obj1, obj2):\n \"\"\"Implementation of object equality.\"\"\"\n raise NotImplementedError()\n"
] |
class BaseComparator(object):
"""Abstract base class for Entity Comparison."""
def __init__(self, l1, l2):
"""
Args:
l1: First list of entities.
l2: Second list of entities.
"""
self.l1 = l1
self.l2 = l2
self.matches = set()
self.process_lists()
def equal(self, obj1, obj2):
"""Implementation of object equality."""
raise NotImplementedError()
def get_matches(self, src, src_idx):
"""Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0]
"""
if src not in ('l1', 'l2'):
raise ValueError('Must have one of "l1" or "l2" as src')
if src == 'l1':
target_list = self.l2
else:
target_list = self.l1
comparator = {
'l1': lambda s_idx, t_idx: (s_idx, t_idx) in self.matches,
'l2': lambda s_idx, t_idx: (t_idx, s_idx) in self.matches,
}[src]
return [(trg_idx, obj) for trg_idx, obj in enumerate(target_list)
if comparator(src_idx, trg_idx)]
|
inveniosoftware-contrib/json-merger
|
json_merger/comparator.py
|
BaseComparator.get_matches
|
python
|
def get_matches(self, src, src_idx):
if src not in ('l1', 'l2'):
raise ValueError('Must have one of "l1" or "l2" as src')
if src == 'l1':
target_list = self.l2
else:
target_list = self.l1
comparator = {
'l1': lambda s_idx, t_idx: (s_idx, t_idx) in self.matches,
'l2': lambda s_idx, t_idx: (t_idx, s_idx) in self.matches,
}[src]
return [(trg_idx, obj) for trg_idx, obj in enumerate(target_list)
if comparator(src_idx, trg_idx)]
|
Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0]
|
train
|
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L56-L74
| null |
class BaseComparator(object):
"""Abstract base class for Entity Comparison."""
def __init__(self, l1, l2):
"""
Args:
l1: First list of entities.
l2: Second list of entities.
"""
self.l1 = l1
self.l2 = l2
self.matches = set()
self.process_lists()
def process_lists(self):
"""Do any preprocessing of the lists."""
for l1_idx, obj1 in enumerate(self.l1):
for l2_idx, obj2 in enumerate(self.l2):
if self.equal(obj1, obj2):
self.matches.add((l1_idx, l2_idx))
def equal(self, obj1, obj2):
"""Implementation of object equality."""
raise NotImplementedError()
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.set_options
|
python
|
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
|
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L39-L47
| null |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.xml2object
|
python
|
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
|
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L64-L80
|
[
"def xml_filter(self, content):\n r\"\"\"Filter and preprocess xml content\n\n :param content: xml content\n :rtype: str\n \"\"\"\n content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()\n\n if not self.__options['encoding']:\n encoding = self.guess_xml_encoding(content) or self.__encoding\n self.set_options(encoding=encoding)\n\n if self.__options['encoding'].lower() != self.__encoding:\n # 编码转换去除xml头\n content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))\n\n if self.__options['unescape']:\n content = utils.html_entity_decode(content)\n return content\n",
"def parse(self, element):\n r\"\"\"Parse xml element.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n \"\"\"\n values = {}\n for child in element:\n node = self.get_node(child)\n subs = self.parse(child)\n value = subs or node['value']\n if node['tag'] not in values:\n values[node['tag']] = value\n else:\n if not isinstance(values[node['tag']], list):\n values[node['tag']] = [values.pop(node['tag'])]\n values[node['tag']].append(value)\n return values\n",
"def parse_full(self, element):\n r\"\"\"Parse xml element include the node attributes.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n\n .. versionadded:: 1.2.1\n \"\"\"\n values = collections.defaultdict(dict)\n for child in element:\n node = self.get_node(child)\n subs = self.parse_full(child)\n value = subs or {'values': node['value']}\n value['attrs'] = node['attr']\n if node['tag'] not in values['values']:\n values['values'][node['tag']] = value\n else:\n if not isinstance(values['values'][node['tag']], list):\n values['values'][node['tag']] = [values['values'].pop(node['tag'])]\n values['values'][node['tag']].append(value)\n return values\n",
"def get_node(self, element):\n r\"\"\"Get node info.\n\n Parse element and get the element tag info. Include tag name, value, attribute, namespace.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n \"\"\"\n ns, tag = self.split_namespace(element.tag)\n return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}\n"
] |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.xml_filter
|
python
|
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
|
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L82-L100
|
[
"def strip_whitespace(s, strict=False):\n s = s.replace('\\r', '').replace('\\n', '').replace('\\t', '').replace('\\x0B', '')\n return s.strip() if strict else s\n",
"def html_entity_decode(s):\n return HTML_ENTITY_PATTERN.sub(html_entity_decode_char, s)\n",
"def set_options(self, **kw):\n r\"\"\"Set Parser options.\n\n .. seealso::\n ``kw`` argument have the same meaning as in :func:`lazyxml.loads`\n \"\"\"\n for k, v in kw.iteritems():\n if k in self.__options:\n self.__options[k] = v\n",
"def guess_xml_encoding(self, content):\n r\"\"\"Guess encoding from xml header declaration.\n\n :param content: xml content\n :rtype: str or None\n \"\"\"\n matchobj = self.__regex['xml_encoding'].match(content)\n return matchobj and matchobj.group(1).lower()\n",
"def strip_xml_header(self, content):\n r\"\"\"Strip xml header\n\n :param content: xml content\n :rtype: str\n \"\"\"\n return self.__regex['xml_header'].sub('', content)\n"
] |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.guess_xml_encoding
|
python
|
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
|
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L102-L109
| null |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.parse
|
python
|
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
|
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L119-L136
|
[
"def parse(self, element):\n r\"\"\"Parse xml element.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n \"\"\"\n values = {}\n for child in element:\n node = self.get_node(child)\n subs = self.parse(child)\n value = subs or node['value']\n if node['tag'] not in values:\n values[node['tag']] = value\n else:\n if not isinstance(values[node['tag']], list):\n values[node['tag']] = [values.pop(node['tag'])]\n values[node['tag']].append(value)\n return values\n",
"def get_node(self, element):\n r\"\"\"Get node info.\n\n Parse element and get the element tag info. Include tag name, value, attribute, namespace.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n \"\"\"\n ns, tag = self.split_namespace(element.tag)\n return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}\n"
] |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.parse_full
|
python
|
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
|
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L138-L158
|
[
"def parse_full(self, element):\n r\"\"\"Parse xml element include the node attributes.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n\n .. versionadded:: 1.2.1\n \"\"\"\n values = collections.defaultdict(dict)\n for child in element:\n node = self.get_node(child)\n subs = self.parse_full(child)\n value = subs or {'values': node['value']}\n value['attrs'] = node['attr']\n if node['tag'] not in values['values']:\n values['values'][node['tag']] = value\n else:\n if not isinstance(values['values'][node['tag']], list):\n values['values'][node['tag']] = [values['values'].pop(node['tag'])]\n values['values'][node['tag']].append(value)\n return values\n",
"def get_node(self, element):\n r\"\"\"Get node info.\n\n Parse element and get the element tag info. Include tag name, value, attribute, namespace.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n \"\"\"\n ns, tag = self.split_namespace(element.tag)\n return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}\n"
] |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.get_node
|
python
|
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
|
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L160-L169
|
[
"def split_namespace(self, tag):\n r\"\"\"Split tag namespace.\n\n :param tag: tag name\n :return: a pair of (namespace, tag)\n :rtype: tuple\n \"\"\"\n matchobj = self.__regex['xml_ns'].search(tag)\n return matchobj.groups() if matchobj else ('', tag)\n"
] |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
heronotears/lazyxml
|
lazyxml/parser.py
|
Parser.split_namespace
|
python
|
def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag)
|
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L171-L179
| null |
class Parser(object):
r"""XML Parser
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__regex = {
'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象
'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象
'xml_encoding': re.compile(r'<\?xml\s+.*?encoding="(.*?)".*?\?>', re.I|re.S) # XML编码声明正则匹配对象
}
self.__options = {
'encoding': None, # XML编码
'unescape': False, # 是否转换HTML实体
'strip_root': True, # 是否去除根节点
'strip_attr': True, # 是否去除节点属性
'strip': True, # 是否去除空白字符(换行符、制表符)
'errors': 'strict', # 解码错误句柄 参见: Codec Base Classes
}
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Parser options.
"""
return self.__options
def xml2dict(self, content):
r"""Convert xml content to dict.
.. warning::
**DEPRECATED:** :meth:`xml2dict` is deprecated. Please use :meth:`xml2object` instead.
.. deprecated:: 1.2
"""
return self.xml2object(content)
def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['strip_attr'] else self.parse_full(element)
if not self.__options['strip_root']:
node = self.get_node(element)
if not self.__options['strip_attr']:
tree['attrs'] = node['attr']
return {node['tag']: tree}
return tree
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = self.guess_xml_encoding(content) or self.__encoding
self.set_options(encoding=encoding)
if self.__options['encoding'].lower() != self.__encoding:
# 编码转换去除xml头
content = self.strip_xml_header(content.decode(self.__options['encoding'], errors=self.__options['errors']))
if self.__options['unescape']:
content = utils.html_entity_decode(content)
return content
def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower()
def strip_xml_header(self, content):
r"""Strip xml header
:param content: xml content
:rtype: str
"""
return self.__regex['xml_header'].sub('', content)
def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs or node['value']
if node['tag'] not in values:
values[node['tag']] = value
else:
if not isinstance(values[node['tag']], list):
values[node['tag']] = [values.pop(node['tag'])]
values[node['tag']].append(value)
return values
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
node = self.get_node(child)
subs = self.parse_full(child)
value = subs or {'values': node['value']}
value['attrs'] = node['attr']
if node['tag'] not in values['values']:
values['values'][node['tag']] = value
else:
if not isinstance(values['values'][node['tag']], list):
values['values'][node['tag']] = [values['values'].pop(node['tag'])]
values['values'][node['tag']].append(value)
return values
def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
return {'tag': tag, 'value': (element.text or '').strip(), 'attr': element.attrib, 'namespace': ns}
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.object2xml
|
python
|
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
|
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L60-L85
|
[
"def set_options(self, **kw):\n r\"\"\"Set Builder options.\n\n .. seealso::\n ``kw`` argument have the same meaning as in :func:`lazyxml.dumps`\n \"\"\"\n for k, v in kw.iteritems():\n if k in self.__options:\n self.__options[k] = v\n",
"def build_xml_header(self):\n r\"\"\"Build xml header include version and encoding.\n\n :rtype: str\n \"\"\"\n return '<?xml version=\"%s\" encoding=\"%s\"?>' % (self.__options['version'], self.__options['encoding'])\n",
"def build_tree(self, data, tagname, attrs=None, depth=0):\n r\"\"\"Build xml tree.\n\n :param data: data for build xml.\n :param tagname: element tag name.\n :param attrs: element attributes. Default:``None``.\n :type attrs: dict or None\n :param depth: element depth of the hierarchy. Default:``0``.\n :type depth: int\n \"\"\"\n if data is None:\n data = ''\n indent = ('\\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''\n if isinstance(data, utils.DictTypes):\n if self.__options['hasattr'] and self.check_structure(data.keys()):\n attrs, values = self.pickdata(data)\n self.build_tree(values, tagname, attrs, depth)\n else:\n self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))\n iter = data.iteritems()\n if self.__options['ksort']:\n iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])\n for k, v in iter:\n attrs = {}\n if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):\n attrs, v = self.pickdata(v)\n self.build_tree(v, k, attrs, depth+1)\n self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))\n elif utils.is_iterable(data):\n for v in data:\n self.build_tree(v, tagname, attrs, depth)\n else:\n self.__tree.append(indent)\n data = self.safedata(data, self.__options['cdata'])\n self.__tree.append(self.build_tag(tagname, data, attrs))\n"
] |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.build_tree
|
python
|
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
|
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L94-L128
| null |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.check_structure
|
python
|
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
|
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L130-L133
| null |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.pickdata
|
python
|
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
|
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L135-L143
| null |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.safedata
|
python
|
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
|
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L145-L154
| null |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.build_tag
|
python
|
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
|
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L156-L165
|
[
"def tag_start(self, tag, attrs=None):\n r\"\"\"Build started tag info.\n\n :param tag: tag name\n :param attrs: tag attributes. Default:``None``.\n :type attrs: dict or None\n :rtype: str\n \"\"\"\n return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag\n",
"def tag_end(self, tag):\n r\"\"\"Build closed tag info.\n\n :param tag: tag name\n :rtype: str\n \"\"\"\n return '</%s>' % tag\n"
] |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.build_attr
|
python
|
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
|
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L167-L175
| null |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
lazyxml/builder.py
|
Builder.tag_start
|
python
|
def tag_start(self, tag, attrs=None):
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
|
r"""Build started tag info.
:param tag: tag name
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L177-L185
|
[
"def build_attr(self, attrs):\n r\"\"\"Build tag attributes.\n\n :param attrs: tag attributes\n :type attrs: dict\n :rtype: str\n \"\"\"\n attrs = sorted(attrs.iteritems(), key=lambda x: x[0])\n return ' '.join(map(lambda x: '%s=\"%s\"' % x, attrs))\n"
] |
class Builder(object):
r"""XML Builder
"""
def __init__(self, **kw):
self.__encoding = 'utf-8' # 内部默认编码: utf-8
self.__options = {
'encoding': None, # XML编码
'header_declare': True, # 是否声明XML头部
'version': '1.0', # XML版本号
'root': None, # XML根节点
'cdata': True, # 是否使用XML CDATA格式
'indent': None, # XML层次缩进
'ksort': False, # XML标签是否排序
'reverse': False, # XML标签排序时是否倒序
'errors': 'strict', # 编码错误句柄 参见: Codec Base Classes
'hasattr': False, # 是否包含属性
'attrkey': '{attrs}', # 标签属性标识key
'valuekey': '{values}' # 标签值标识key
}
self.__tree = []
self.set_options(**kw)
def set_options(self, **kw):
r"""Set Builder options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.dumps`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v
def get_options(self):
r"""Get Builder options.
"""
return self.__options
def dict2xml(self, data):
r"""Convert dict to xml.
.. warning::
**DEPRECATED:** :meth:`dict2xml` is deprecated. Please use :meth:`object2xml` instead.
.. deprecated:: 1.2
"""
return self.object2xml(data)
def object2xml(self, data):
r"""Convert python object to xml string.
:param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``.
:rtype: str or unicode
.. versionadded:: 1.2
"""
if not self.__options['encoding']:
self.set_options(encoding=self.__encoding)
if self.__options['header_declare']:
self.__tree.append(self.build_xml_header())
root = self.__options['root']
if not root:
assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
'if root not specified, the data that dict object and length must be one required.'
root, data = data.items()[0]
self.build_tree(data, root)
xml = unicode(''.join(self.__tree).strip())
if self.__options['encoding'] != self.__encoding:
xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
return xml
def build_xml_header(self):
r"""Build xml header include version and encoding.
:rtype: str
"""
return '<?xml version="%s" encoding="%s"?>' % (self.__options['version'], self.__options['encoding'])
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int
"""
if data is None:
data = ''
indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else ''
if isinstance(data, utils.DictTypes):
if self.__options['hasattr'] and self.check_structure(data.keys()):
attrs, values = self.pickdata(data)
self.build_tree(values, tagname, attrs, depth)
else:
self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs)))
iter = data.iteritems()
if self.__options['ksort']:
iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse'])
for k, v in iter:
attrs = {}
if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()):
attrs, v = self.pickdata(v)
self.build_tree(v, k, attrs, depth+1)
self.__tree.append('%s%s' % (indent, self.tag_end(tagname)))
elif utils.is_iterable(data):
for v in data:
self.build_tree(v, tagname, attrs, depth)
else:
self.__tree.append(indent)
data = self.safedata(data, self.__options['cdata'])
self.__tree.append(self.build_tag(tagname, data, attrs))
def check_structure(self, keys):
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
"""
return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
def pickdata(self, data):
r"""Pick data from ``attrkey`` and ``valuekey`` option.
:return: a pair of (attrs, values)
:rtype: tuple
"""
attrs = data.get(self.__options['attrkey']) or {}
values = data.get(self.__options['valuekey']) or ''
return (attrs, values)
def safedata(self, data, cdata=True):
r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str
"""
safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True)
return safe
def build_tag(self, tag, text='', attrs=None):
r"""Build tag full info include the attributes.
:param tag: tag name.
:param text: tag text.
:param attrs: tag attributes. Default:``None``.
:type attrs: dict or None
:rtype: str
"""
return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
def build_attr(self, attrs):
r"""Build tag attributes.
:param attrs: tag attributes
:type attrs: dict
:rtype: str
"""
attrs = sorted(attrs.iteritems(), key=lambda x: x[0])
return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
def tag_end(self, tag):
r"""Build closed tag info.
:param tag: tag name
:rtype: str
"""
return '</%s>' % tag
|
heronotears/lazyxml
|
demo/dump.py
|
main
|
python
|
def main():
data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}}
# xml写入文件 提供文件名
lazyxml.dump(data, 'xml/dump.xml')
# xml写入文件 提供文件句柄
with open('xml/dump-fp.xml', 'w') as fp:
lazyxml.dump(data, fp)
# xml写入文件 提供类文件对象
from cStringIO import StringIO
buffer = StringIO()
lazyxml.dump(data, buffer)
print buffer.getvalue()
# <?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[1]]></foo><bar><![CDATA[2]]></bar></demo>
buffer.close()
# 默认
print lazyxml.dumps(data)
# '<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'
# 不声明xml头部
print lazyxml.dumps(data, header_declare=False)
# '<demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'
# 不使用CDATA格式
print lazyxml.dumps(data, cdata=False)
# '<?xml version="1.0" encoding="utf-8"?><demo><foo><foo></foo><bar>1</bar><bar>2</bar></demo>'
# 缩进和美观xml
print lazyxml.dumps(data, indent=' ' * 4)
# <?xml version="1.0" encoding="utf-8"?>
# <demo>
# <foo><![CDATA[<foo>]]></foo>
# <bar><![CDATA[1]]></bar>
# <bar><![CDATA[2]]></bar>
# </demo>
# 使用标签名称排序
print lazyxml.dumps(data, ksort=True)
# '<?xml version="1.0" encoding="utf-8"?><demo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar><foo><![CDATA[<foo>]]></foo></demo>'
# 使用标签名称倒序排序
print lazyxml.dumps(data, ksort=True, reverse=True)
# '<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'
# 含有属性的xml数据
kw = {
'hasattr': True,
'ksort': True,
'indent': ' ' * 4,
'attrkey': ATTRKEY,
'valuekey': VALUEKEY
}
print lazyxml.dumps(ATTRDATA, **kw)
"""
<root a1="1" a2="2">
<test1 a="1" b="2" c="3">
<normal index="5" required="false">
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
<foo><![CDATA[<foo-1>]]></foo>
</normal>
<repeat1 index="1" required="false">
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
<foo><![CDATA[<foo-1>]]></foo>
</repeat1>
<repeat1 index="1" required="false">
<bar><![CDATA[3]]></bar>
<bar><![CDATA[4]]></bar>
<foo><![CDATA[<foo-2>]]></foo>
</repeat1>
<repeat2 index="2" required="true"><![CDATA[1]]></repeat2>
<repeat2 index="2" required="true"><![CDATA[2]]></repeat2>
<repeat3 index="3" required="true">
<sub><![CDATA[1]]></sub>
<sub><![CDATA[2]]></sub>
</repeat3>
<repeat3 index="4" required="true">
<sub><![CDATA[1]]></sub>
<sub><![CDATA[2]]></sub>
<sub><![CDATA[3]]></sub>
</repeat3>
</test1>
<test2 a="1" b="2" c="3"><![CDATA[测试用]]></test2>
</root>
"""
|
<root a1="1" a2="2">
<test1 a="1" b="2" c="3">
<normal index="5" required="false">
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
<foo><![CDATA[<foo-1>]]></foo>
</normal>
<repeat1 index="1" required="false">
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
<foo><![CDATA[<foo-1>]]></foo>
</repeat1>
<repeat1 index="1" required="false">
<bar><![CDATA[3]]></bar>
<bar><![CDATA[4]]></bar>
<foo><![CDATA[<foo-2>]]></foo>
</repeat1>
<repeat2 index="2" required="true"><![CDATA[1]]></repeat2>
<repeat2 index="2" required="true"><![CDATA[2]]></repeat2>
<repeat3 index="3" required="true">
<sub><![CDATA[1]]></sub>
<sub><![CDATA[2]]></sub>
</repeat3>
<repeat3 index="4" required="true">
<sub><![CDATA[1]]></sub>
<sub><![CDATA[2]]></sub>
<sub><![CDATA[3]]></sub>
</repeat3>
</test1>
<test2 a="1" b="2" c="3"><![CDATA[测试用]]></test2>
</root>
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/demo/dump.py#L54-L142
|
[
"def dump(obj, fp, **kw):\n r\"\"\"Dump python object to file.\n\n >>> import lazyxml\n >>> data = {'demo': {'foo': 1, 'bar': 2}}\n >>> lazyxml.dump(data, 'dump.xml')\n >>> with open('dump-fp.xml', 'w') as fp:\n >>> lazyxml.dump(data, fp)\n\n >>> from cStringIO import StringIO\n >>> data = {'demo': {'foo': 1, 'bar': 2}}\n >>> buffer = StringIO()\n >>> lazyxml.dump(data, buffer)\n >>> buffer.getvalue()\n <?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><![CDATA[1]]></foo><bar><![CDATA[2]]></bar></demo>\n >>> buffer.close()\n\n .. note::\n ``kw`` argument have the same meaning as in :func:`dumps`\n\n :param obj: data for dump to xml.\n :param fp: a filename or a file or file-like object that support ``.write()`` to write the xml content\n\n .. versionchanged:: 1.2\n The `fp` is a filename of string before this. It can now be a file or file-like object that support ``.write()`` to write the xml content.\n \"\"\"\n xml = dumps(obj, **kw)\n if isinstance(fp, basestring):\n with open(fp, 'w') as fobj:\n fobj.write(xml)\n else:\n fp.write(xml)\n",
"def dumps(obj, **kw):\n r\"\"\"Dump python object to xml.\n\n >>> import lazyxml\n\n >>> data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}}\n\n >>> lazyxml.dumps(data)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'\n\n >>> lazyxml.dumps(data, header_declare=False)\n '<demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'\n\n >>> lazyxml.dumps(data, cdata=False)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><foo></foo><bar>1</bar><bar>2</bar></demo>'\n\n >>> print lazyxml.dumps(data, indent=' ' * 4)\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <demo>\n <foo><![CDATA[<foo>]]></foo>\n <bar><![CDATA[1]]></bar>\n <bar><![CDATA[2]]></bar>\n </demo>\n\n >>> lazyxml.dumps(data, ksort=True)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar><foo><![CDATA[<foo>]]></foo></demo>'\n\n >>> lazyxml.dumps(data, ksort=True, reverse=True)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'\n\n .. note::\n Data that has attributes convert to xml see ``demo/dump.py``.\n\n :param obj: data for dump to xml.\n\n ``kw`` arguments below here.\n\n :param encoding: XML编码 默认:``utf-8``.\n :param header_declare: 是否声明XML头部 默认:``True``.\n :type header_declare: bool\n :type version: XML版本号 默认:``1.0``.\n :param root: XML根节点 默认:``None``.\n :param cdata: 是否使用XML CDATA格式 默认:``True``.\n :type cdata: bool\n :param indent: XML层次缩进 默认:``None``.\n :param ksort: XML标签是否排序 默认:``False``.\n :type ksort: bool\n :param reverse: XML标签排序时是否倒序 默认:``False``.\n :type reverse: bool\n :param errors: 解码错误句柄 see: :meth:`str.decode` 默认:``strict``.\n :param hasattr: 是否包含属性 默认:``False``.\n :type hasattr: bool\n :param attrkey: 标签属性标识key 默认:``{attrs}``.\n :param valuekey: 标签值标识key 默认:``{values}``.\n :rtype: str\n \"\"\"\n return builder.Builder(**kw).object2xml(obj)\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import compat
import lazyxml
ATTRKEY = '{{attrs}}'
VALUEKEY = '{{values}}'
ATTRDATA = {
'root': {
ATTRKEY: {'a1': 1, 'a2': 2},
VALUEKEY: {
'test1': {
ATTRKEY: {'b': 2, 'a': 1, 'c': 3},
VALUEKEY: {
# 重复方式-1: 所有的重复使用相同的属性(子节点重复)
'repeat1': {
ATTRKEY: {'required': 'false', 'index': 1},
VALUEKEY: [{'foo': '<foo-1>', 'bar': ['1', '2']}, {'foo': '<foo-2>', 'bar': ['3', '4']}]
},
# 重复方式-2: 所有的重复使用相同的属性(当前节点重复)
'repeat2': {
ATTRKEY: {'required': 'true', 'index': '2'},
VALUEKEY: [1, 2]
},
# 重复方式-3: 同一个节点使用不同的属性
'repeat3': [
{
ATTRKEY: {'required': 'true', 'index': '3'},
VALUEKEY: {'sub': [1, 2]}
},
{
ATTRKEY: {'required': 'true', 'index': '4'},
VALUEKEY: {'sub': [1, 2, 3]}
},
],
'normal': {
ATTRKEY: {'required': 'false', 'index': 5},
VALUEKEY: {'foo': '<foo-1>', 'bar': ['1', '2']}
}
}
},
'test2': {
ATTRKEY: {'b': 2, 'a': 1, 'c': 3},
VALUEKEY: u'测试用'
}
}
}
}
if __name__ == '__main__':
main()
|
heronotears/lazyxml
|
lazyxml/__init__.py
|
dump
|
python
|
def dump(obj, fp, **kw):
r"""Dump python object to file.
>>> import lazyxml
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> lazyxml.dump(data, 'dump.xml')
>>> with open('dump-fp.xml', 'w') as fp:
>>> lazyxml.dump(data, fp)
>>> from cStringIO import StringIO
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> buffer = StringIO()
>>> lazyxml.dump(data, buffer)
>>> buffer.getvalue()
<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[1]]></foo><bar><![CDATA[2]]></bar></demo>
>>> buffer.close()
.. note::
``kw`` argument have the same meaning as in :func:`dumps`
:param obj: data for dump to xml.
:param fp: a filename or a file or file-like object that support ``.write()`` to write the xml content
.. versionchanged:: 1.2
The `fp` is a filename of string before this. It can now be a file or file-like object that support ``.write()`` to write the xml content.
"""
xml = dumps(obj, **kw)
if isinstance(fp, basestring):
with open(fp, 'w') as fobj:
fobj.write(xml)
else:
fp.write(xml)
|
r"""Dump python object to file.
>>> import lazyxml
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> lazyxml.dump(data, 'dump.xml')
>>> with open('dump-fp.xml', 'w') as fp:
>>> lazyxml.dump(data, fp)
>>> from cStringIO import StringIO
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> buffer = StringIO()
>>> lazyxml.dump(data, buffer)
>>> buffer.getvalue()
<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[1]]></foo><bar><![CDATA[2]]></bar></demo>
>>> buffer.close()
.. note::
``kw`` argument have the same meaning as in :func:`dumps`
:param obj: data for dump to xml.
:param fp: a filename or a file or file-like object that support ``.write()`` to write the xml content
.. versionchanged:: 1.2
The `fp` is a filename of string before this. It can now be a file or file-like object that support ``.write()`` to write the xml content.
|
train
|
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/__init__.py#L149-L180
|
[
"def dumps(obj, **kw):\n r\"\"\"Dump python object to xml.\n\n >>> import lazyxml\n\n >>> data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}}\n\n >>> lazyxml.dumps(data)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'\n\n >>> lazyxml.dumps(data, header_declare=False)\n '<demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'\n\n >>> lazyxml.dumps(data, cdata=False)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><foo></foo><bar>1</bar><bar>2</bar></demo>'\n\n >>> print lazyxml.dumps(data, indent=' ' * 4)\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <demo>\n <foo><![CDATA[<foo>]]></foo>\n <bar><![CDATA[1]]></bar>\n <bar><![CDATA[2]]></bar>\n </demo>\n\n >>> lazyxml.dumps(data, ksort=True)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar><foo><![CDATA[<foo>]]></foo></demo>'\n\n >>> lazyxml.dumps(data, ksort=True, reverse=True)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'\n\n .. note::\n Data that has attributes convert to xml see ``demo/dump.py``.\n\n :param obj: data for dump to xml.\n\n ``kw`` arguments below here.\n\n :param encoding: XML编码 默认:``utf-8``.\n :param header_declare: 是否声明XML头部 默认:``True``.\n :type header_declare: bool\n :type version: XML版本号 默认:``1.0``.\n :param root: XML根节点 默认:``None``.\n :param cdata: 是否使用XML CDATA格式 默认:``True``.\n :type cdata: bool\n :param indent: XML层次缩进 默认:``None``.\n :param ksort: XML标签是否排序 默认:``False``.\n :type ksort: bool\n :param reverse: XML标签排序时是否倒序 默认:``False``.\n :type reverse: bool\n :param errors: 解码错误句柄 see: :meth:`str.decode` 默认:``strict``.\n :param hasattr: 是否包含属性 默认:``False``.\n :type hasattr: bool\n :param attrkey: 标签属性标识key 默认:``{attrs}``.\n :param valuekey: 标签值标识key 默认:``{values}``.\n :rtype: str\n \"\"\"\n return builder.Builder(**kw).object2xml(obj)\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @package lazyxml
# @copyright Copyright (c) 2012, Zonglong Fan.
# @license MIT
r"""A simple xml parse and build lib.
"""
from __future__ import with_statement, absolute_import
from . import builder
from . import parser
__author__ = 'Zonglong Fan <lazyboy.fan@gmail.com>'
__version__ = '1.2.1'
def loads(content, **kw):
r"""Load xml content to python object.
>>> import lazyxml
>>> xml = '<demo><foo>foo</foo><bar>bar</bar></demo>'
>>> lazyxml.loads(xml)
{'bar': 'bar', 'foo': 'foo'}
>>> xml = '<demo><foo>foo</foo><bar>bar</bar></demo>'
>>> lazyxml.loads(xml, strip_root=False)
{'demo': {'bar': 'bar', 'foo': 'foo'}}
>>> xml = '<demo><foo>foo</foo><bar>1</bar><bar>2</bar></demo>'
>>> lazyxml.loads(xml)
{'bar': ['1', '2'], 'foo': 'foo'}
>>> xml = '<root xmlns:h="http://www.w3.org/TR/html4/"><demo><foo>foo</foo><bar>bar</bar></demo></root>'
>>> lazyxml.loads(xml, unescape=True, strip_root=False)
{'root': {'demo': {'bar': 'bar', 'foo': 'foo'}}}
:param content: xml content
:type content: str
``kw`` arguments below here.
:param encoding: XML编码 默认:``utf-8``.
:param unescape: 是否转换HTML实体 默认:``False``.
:type unescape: bool
:param strip_root: 是否去除根节点 默认:``True``.
:type strip_root: bool
:param strip_attr: 是否去除节点属性 默认:``True``.
:type strip_attr: bool
:param strip: 是否去除空白字符(换行符、制表符) 默认:``True``.
:type strip: bool
:param errors: 解码错误句柄 参考: :meth:`str.decode` 默认:``strict``.
:rtype: dict
.. versionchanged:: 1.2.1
The ``strip_attr`` option supported to decide whether return the element attributes for parse result.
"""
return parser.Parser(**kw).xml2object(content)
def load(fp, **kw):
r"""Load xml content from file and convert to python object.
>>> import lazyxml
>>> with open('demo.xml', 'rb') as fp:
>>> lazyxml.load(fp)
>>> from cStringIO import StringIO
>>> buffer = StringIO('<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>')
>>> lazyxml.load(buffer)
{'bar': ['1', '2'], 'foo': '<foo>'}
>>> buffer.close()
.. note::
``kw`` argument have the same meaning as in :func:`loads`
:param fp: a file or file-like object that support ``.read()`` to read the xml content
:rtype: dict
"""
content = fp.read()
return loads(content, **kw)
def dumps(obj, **kw):
r"""Dump python object to xml.
>>> import lazyxml
>>> data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}}
>>> lazyxml.dumps(data)
'<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'
>>> lazyxml.dumps(data, header_declare=False)
'<demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'
>>> lazyxml.dumps(data, cdata=False)
'<?xml version="1.0" encoding="utf-8"?><demo><foo><foo></foo><bar>1</bar><bar>2</bar></demo>'
>>> print lazyxml.dumps(data, indent=' ' * 4)
<?xml version="1.0" encoding="utf-8"?>
<demo>
<foo><![CDATA[<foo>]]></foo>
<bar><![CDATA[1]]></bar>
<bar><![CDATA[2]]></bar>
</demo>
>>> lazyxml.dumps(data, ksort=True)
'<?xml version="1.0" encoding="utf-8"?><demo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar><foo><![CDATA[<foo>]]></foo></demo>'
>>> lazyxml.dumps(data, ksort=True, reverse=True)
'<?xml version="1.0" encoding="utf-8"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></demo>'
.. note::
Data that has attributes convert to xml see ``demo/dump.py``.
:param obj: data for dump to xml.
``kw`` arguments below here.
:param encoding: XML编码 默认:``utf-8``.
:param header_declare: 是否声明XML头部 默认:``True``.
:type header_declare: bool
:type version: XML版本号 默认:``1.0``.
:param root: XML根节点 默认:``None``.
:param cdata: 是否使用XML CDATA格式 默认:``True``.
:type cdata: bool
:param indent: XML层次缩进 默认:``None``.
:param ksort: XML标签是否排序 默认:``False``.
:type ksort: bool
:param reverse: XML标签排序时是否倒序 默认:``False``.
:type reverse: bool
:param errors: 解码错误句柄 see: :meth:`str.decode` 默认:``strict``.
:param hasattr: 是否包含属性 默认:``False``.
:type hasattr: bool
:param attrkey: 标签属性标识key 默认:``{attrs}``.
:param valuekey: 标签值标识key 默认:``{values}``.
:rtype: str
"""
return builder.Builder(**kw).object2xml(obj)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.