code
stringlengths
1
18.2k
urls: self.__remove_URL_from_10320LOC(url, list_of_entries, handle) op = 'removing URLs' resp, put_payload = self.__send_handle_put_request( handle, list_of_entries, overwrite=True, op=op ) # TODO FIXME (one day): Implement overwriting by index (less risky), # once HS have fixed the issue with the indices. if hsrespons...
msg=msg, payload=put_payload )
def register_handle(self, handle, location, checksum=None, additional_URLs=None, overwrite=False, **extratypes): ''' Registers a new Handle with given name. If the handle already exists and overwrite is not set to True, the method will throw an exception. :param handle: The full name of the handle to be registered (pre...
string. :param extratypes: Optional. Additional key value pairs. :param additional_URLs: Optional. A list of URLs (as strings) to be added to the handle record as 10320/LOC entry. :param overwrite: Optional. If set to True, an existing handle record will be overwritten. Defaults to False. :raises: :exc:`~b2handle.handl...
''' LOGGER.debug('register_handle...') # If already exists and can't be overwritten: if overwrite == False: handlerecord_json = self.retrieve_handle_record_json(handle) if handlerecord_json is not None: msg = 'Could not register handle' LOGGER.error(msg + ', as it already exists.') raise HandleAlreadyExistsException(ha...
self.__make_another_index(list_of_entries, url=True) ) list_of_entries.append(entry_URL) if checksum is not None: entryChecksum = self.__create_entry( 'CHECKSUM', checksum, self.__make_another_index(list_of_entries) ) list_of_entries.append(entryChecksum) if extratypes is not None: for key, value in extratypes.items():...
put_payload = self.__send_handle_put_request( handle, list_of_entries, overwrite=overwrite, op=op ) resp_content = decoded_response(resp) if hsresponses.was_handle_created(resp) or hsresponses.handle_success(resp): LOGGER.info("Handle registered: " + handle) return json.loads(resp_content)['handle'] elif hsresponses.is...
you used HTTP instead of HTTPS?' ) else: raise GenericHandleError( operation=op, handle=handle, reponse=resp, payload=put_payload )
def search_handle(self, URL=None, prefix=None, **key_value_pairs): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handl...
specified, all key-value pairs are passed on to the reverse lookup servlet, possibly causing a :exc:`~b2handle.handleexceptions.ReverseLookupException`. Example calls: .. code:: python list_of_handles = search_handle('http://www.foo.com') list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999) list_of_han...
to. If unspecified, the method will search across all prefixes present at the server given to the constructor. :param key_value_pairs: Optional. Several search fields and values can be specified as key-value-pairs, e.g. CHECKSUM=123456, URL=www.foo.com :raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: I...
with given value of given prefix or server. The list may be empty and may also contain more than one element. ''' LOGGER.debug('search_handle...') list_of_handles = self.__searcher.search_handle(URL=URL, prefix=prefix, **key_value_pairs) return list_of_handles
def generate_PID_name(self, prefix=None): ''' Generate a unique random Handle name (random UUID). The Handle is not registered. If a prefix is specified, the PID name has the syntax <prefix>/<generatedname>, otherwise it just returns the generated random name (suffix for the Handle). :param prefix: Optional. The prefix...
LOGGER.debug('generate_PID_name...') randomuuid = uuid.uuid4() if prefix is not None: return prefix + '/' + str(randomuuid) else: return str(randomuuid)
def get_handlerecord_indices_for_key(self, key, list_of_entries): ''' Finds the Handle entry indices of all entries that have a specific type. *Important:* It finds the Handle System indices! These are not the python indices of the list, so they can not be used for iteration. :param key: The key (Handle Record type) :p...
A list of strings, the indices of the entries of type "key" in the given handle record. ''' LOGGER.debug('get_handlerecord_indices_for_key...') indices = [] for entry in list_of_entries: if entry['type'] == key: indices.append(entry['index']) return indices
def __send_handle_delete_request(self, handle, indices=None, op=None): ''' Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A list of indices to delete. Defa...
The server's response. ''' resp = self.__handlesystemconnector.send_handle_delete_request( handle=handle, indices=indices, op=op) return resp
def __send_handle_put_request(self, handle, list_of_entries, indices=None, overwrite=False, op=None): ''' Send a HTTP PUT request to the handle server to write either an entire handle or to some specified values to an handle record, using the requests module. :param handle: The handle. :param list_of_entries: A list of...
of indices to modify. Defaults to None (i.e. the entire handle is updated.). The list can contain integers or strings. :param overwrite: Optional. Whether the handle should be overwritten if it exists already. :return: The server's response. ''' resp, payload = self.__handlesystemconnector.send_handle_put_request( hand...
def __send_handle_get_request(self, handle, indices=None): ''' Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A list of indices to delete. Defaults to None (i.e...
server's response. ''' resp = self.__handlesystemconnector.send_handle_get_request(handle, indices) return resp
def __get_handle_record_if_necessary(self, handle, handlerecord_json): ''' Returns the handle record if it is None or if its handle is not the same as the specified handle. ''' if handlerecord_json is None: handlerecord_json = self.retrieve_handle_record_json(handle) else: if handle != handlerecord_json['handle']: hand...
def __make_another_index(self, list_of_entries, url=False, hs_admin=False): ''' Find an index not yet used in the handle record and not reserved for any (other) special type. :param: list_of_entries: List of all entries to find which indices are used already. :param url: If True, an index for an URL entry is returned (...
is returned (100 or one of the following). :return: An integer. ''' start = 2 # reserved indices: reserved_for_url = set([1]) reserved_for_admin = set(range(100, 200)) prohibited_indices = reserved_for_url | reserved_for_admin if url: prohibited_indices = prohibited_indices - reserved_for_url start = 1 elif hs_admin: p...
list_of_entries: existing_indices.add(int(entry['index'])) # find new index: all_prohibited_indices = existing_indices | prohibited_indices searchmax = max(start, max(all_prohibited_indices)) + 2 for index in xrange(start, searchmax): if index not in all_prohibited_indices: return index
def __create_entry(self, entrytype, data, index, ttl=None): ''' Create an entry of any type except HS_ADMIN. :param entrytype: THe type of entry to create, e.g. 'URL' or 'checksum' or ... Note: For entries of type 'HS_ADMIN', please use __create_admin_entry(). For type '10320/LOC', please use 'add_additional_URL()' :pa...
:param index: The integer to be used as index. :param ttl: Optional. If not set, the library's default is set. If there is no default, it is not set by this library, so Handle System sets it. :return: The entry as a dict. ''' if entrytype == 'HS_ADMIN': op = 'creating HS_ADMIN entry' msg = 'This method can not create H...
msg=msg) entry = {'index':index, 'type':entrytype, 'data':data} if ttl is not None: entry['ttl'] = ttl return entry
def __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None): ''' Create an entry of type "HS_ADMIN". :param username: The username, i.e. a handle with an index (index:prefix/suffix). The value referenced by the index contains authentcation information, e.g. a hidden entry containing a key. :param ...
are set to zero. :param index: The integer to be used as index of this admin entry (not of the username!). Should be 1xx. :param ttl: Optional. If not set, the library's default is set. If there is no default, it is not set by this library, so Handle System sets it. :return: The entry as a dict. ''' # If the handle own...
is specified, use it. Otherwise, use 200:0.NA/prefix # With the prefix taken from the handle that is being created, not from anywhere else. if handleowner is None: adminindex = '200' prefix = handle.split('/')[0] adminhandle = '0.NA/' + prefix else: adminindex, adminhandle = utilhandle.remove_index_from_handle(handleow...
= ttl return entry
def __get_python_indices_for_key(self, key, list_of_entries): ''' Finds the indices of all entries that have a specific type. Important: This method finds the python indices of the list of entries! These are not the Handle System index values! :param key: The key (Handle Record type) :param list_of_entries: A list of t...
of the entries of type "key" in the given list. ''' indices = [] for i in xrange(len(list_of_entries)): if list_of_entries[i]['type'] == key: indices.append(i) return indices
def __exchange_URL_in_13020loc(self, oldurl, newurl, list_of_entries, handle): ''' Exchange every occurrence of oldurl against newurl in a 10320/LOC entry. This does not change the ids or other xml attributes of the <location> element. :param oldurl: The URL that will be overwritten. :param newurl: The URL to write int...
:param handle: Only for the exception message. :raise: GenericHandleError: If several 10320/LOC exist (unlikely). ''' # Find existing 10320/LOC entries python_indices = self.__get_python_indices_for_key( '10320/LOC', list_of_entries ) num_exchanged = 0 if len(python_indices) > 0: if len(python_indices) > 1: msg = str(l...
in all_URL_elements: if element.get('href') == oldurl: LOGGER.debug('__exchange_URL_in_13020loc: Exchanging URL ' + oldurl + ' from 10320/LOC.') num_exchanged += 1 element.set('href', newurl) entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value) list_of_entries.append(entry) if num_exchanged == 0: LOGG...
10320/LOC.' message = message.replace('1 times', 'once') LOGGER.debug(message)
def __remove_URL_from_10320LOC(self, url, list_of_entries, handle): ''' Remove an URL from the handle record's "10320/LOC" entry. If it exists several times in the entry, all occurences are removed. If the URL is not present, nothing happens. If after removing, there is no more URLs in the entry, the entry is removed. ...
entries (to find and remove the correct one). :param handle: Only for the exception message. :raise: GenericHandleError: If several 10320/LOC exist (unlikely). ''' # Find existing 10320/LOC entries python_indices = self.__get_python_indices_for_key( '10320/LOC', list_of_entries ) num_removed = 0 if len(python_indices) ...
xmlroot = ET.fromstring(entry['data']['value']) all_URL_elements = xmlroot.findall('location') for element in all_URL_elements: if element.get('href') == url: LOGGER.debug('__remove_URL_from_10320LOC: Removing URL ' + url + '.') num_removed += 1 xmlroot.remove(element) remaining_URL_elements = xmlroot.findall('location...
became empty! else: entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value) LOGGER.debug('__remove_URL_from_10320LOC: ' + str(len(remaining_URL_elements)) + ' URLs' + \ ' left after removal operation.') list_of_entries.append(entry) if num_removed == 0: LOGGER.debug('__remove_URL_from_10320LOC: No URLs r...
def __add_URL_to_10320LOC(self, url, list_of_entries, handle=None, weight=None, http_role=None, **kvpairs): ''' Add a url to the handle record's "10320/LOC" entry. If no 10320/LOC entry exists, a new one is created (using the default "chooseby" attribute, if configured). If the URL is already present, it is not added a...
thrown (xml.etree.ElementTree.ParseError) Note: In the unlikely case that several "10320/LOC" entries exist, an exception is raised. :param url: The URL to be added. :param list_of_entries: A list of the existing entries (to find and adapt the correct one). :param weight: Optional. The weight to be set (integer between...
accepted range, it is set to 1. :param http_role: Optional. The http_role to be set. This accepts any string. Currently, Handle System can process 'conneg'. In future, it may be able to process 'no_conneg' and 'browser'. :param handle: Optional. Only for the exception message. :param all others: Optional. All other key...
to string. :raise: GenericHandleError: If several 10320/LOC exist (unlikely). ''' # Find existing 10320/LOC entry or create new indices = self.__get_python_indices_for_key('10320/LOC', list_of_entries) makenew = False entry = None if len(indices) == 0: index = self.__make_another_index(list_of_entries) entry = self.__c...
indices[0] entry = list_of_entries.pop(ind) # Get xml data or make new: xmlroot = None if makenew: xmlroot = ET.Element('locations') if self.__10320LOC_chooseby is not None: xmlroot.set('chooseby', self.__10320LOC_chooseby) else: try: xmlroot = ET.fromstring(entry['data']['value']) except TypeError: xmlroot = ET.fromst...
in list_of_locations: try: existing_location_ids.append(int(item.get('id'))) except TypeError: pass if item.get('href') == url: location_element = item existing_location_ids.sort() # ... if not, add it! if location_element is None: location_id = 0 for existing_id in existing_location_ids: if location_id == existing_id:...
(2) " + ET.tostring(location_element, encoding=encoding_value) + ', now add url ' + str(url)) location_element.set('href', url) LOGGER.debug("__add_URL_to_10320LOC: location_element is (3) " + ET.tostring(location_element, encoding=encoding_value)) self.__set_or_adapt_10320LOC_attributes(location_element, weight, http_...
xmlroot is (2) " + ET.tostring(xmlroot, encoding=encoding_value)) entry['data'] = ET.tostring(xmlroot, encoding=encoding_value) list_of_entries.append(entry)
def __set_or_adapt_10320LOC_attributes(self, locelement, weight=None, http_role=None, **kvpairs): ''' Adds or updates attributes of a <location> element. Existing attributes are not removed! :param locelement: A location element as xml snippet (xml.etree.ElementTree.Element). :param weight: Optional. The weight to be s...
Optional. The http_role to be set. This accepts any string. Currently, Handle System can process 'conneg'. In future, it may be able to process 'no_conneg' and 'browser'. :param all others: Optional. All other key-value pairs will be set to the element. Any value is accepted and transformed to string. ''' if weight is ...
str(weight)) weight = float(weight) if weight < 0 or weight > 1: default = 1 LOGGER.debug('__set_or_adapt_10320LOC_attributes: Invalid weight (' + str(weight) + \ '), using default value (' + str(default) + ') instead.') weight = default weight = str(weight) locelement.set('weight', weight) if http_role is not None: lo...
def authorize_url(self): """ authorization url request weibo authorization url :return: code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。 state string 如果传递参数,会回传该参数 """ if self.oauth2_params and self.oauth2_params.get("display") == "mobile": auth_url = self.mobile_url + "authorize" else: auth_url = self.site...
def request(self, method, suffix, data): """ :param method: str, http method ["GET","POST","PUT"] :param suffix: the url suffix :param data: :return: """ url = self.site_url + suffix response = self.session.request(method, url, data=data) if response.status_code == 200: json_obj = response.json() if isinstance(json_obj...
" method:{method}: data={data}".format( code=response.status_code, url=response.url, method=method, data=data ) )
def auth_access(self, auth_code): """ verify the fist authorization response url code response data 返回值字段 字段类型 字段说明 access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据, 第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID 字段来做登录识别。 expires_in string access_token的生命周期,单位是秒数。 remind_in string access_token的生命周期...
self.client_secret, 'grant_type': 'authorization_code', 'code': auth_code, 'redirect_uri': self.redirect_url } return self.request("post", "access_token", data=data)
def revoke_auth_access(self, access_token): """ 授权回收接口,帮助开发者主动取消用户的授权。 应用下线时,清空所有用户的授权 应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权 开发者调试应用,需要反复调试授权功能 应用内实现类似登出微博帐号的功能 并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间 :param access_token: :return: bool """ result = self.request("post", "revokeoauth2", data={"access_toke...
def __set_basic_auth_string(self, username, password): ''' Creates and sets the authentication string for (write-)accessing the Handle Server. No return, the string is set as an attribute to the client instance. :param username: Username handle with index: index:prefix/suffix. :param password: The password contained in...
def send_handle_get_request(self, handle, indices=None): ''' Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A list of indices to delete. Defaults to None (i.e. ...
server's response. ''' # Assemble required info: url = self.make_handle_URL(handle, indices) LOGGER.debug('GET Request to '+url) head = self.__get_headers('GET') veri = self.__HTTPS_verify # Send the request if self.__cert_needed_for_get_request(): # If this is the first request and the connector uses client cert authe...
# Normal case: resp = self.__session.get(url, headers=head, verify=veri) # Log and return self.__log_request_response_to_file( logger=REQUESTLOGGER, op='GET', handle=handle, url=url, headers=head, verify=veri, resp=resp ) self.__first_request = False return resp
def send_handle_put_request(self, **args): ''' Send a HTTP PUT request to the handle server to write either an entire handle or to some specified values to an handle record, using the requests module. :param handle: The handle. :param list_of_entries: A list of handle record entries to be written, in the format [{"inde...
Defaults to None (i.e. the entire handle is deleted.). The list can contain integers or strings. :param overwrite: Optional. Whether the handle should be overwritten if it exists already. :return: The server's response. ''' # Check if we have write access at all: if not self.__has_write_access: raise HandleAuthenticati...
handle = args['handle'] list_of_entries = args['list_of_entries'] indices = args['indices'] op = args['op'] overwrite = args['overwrite'] or False # Make necessary values: url = self.make_handle_URL(handle, indices, overwrite=overwrite) LOGGER.debug('PUT Request to '+url) payload = json.dumps({'values':list_of_entries}...
head, veri, handle, resp) # Check response for authentication issues: if b2handle.hsresponses.not_authenticated(resp): raise HandleAuthenticationError( operation=op, handle=handle, response=resp, username=self.__username ) self.__first_request = False return resp, payload
def send_handle_delete_request(self, **args): ''' Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A list of indices to delete. Defaults to None (i.e. the en...
response. ''' # Check if we have write access at all: if not self.__has_write_access: raise HandleAuthenticationError(msg=self.__no_auth_message) # Check args: mandatory_args = ['handle'] optional_args = ['indices', 'op'] b2handle.util.add_missing_optional_args_with_value_none(args, optional_args) b2handle.util.check_p...
LOGGER.debug('__send_handle_delete_request: Deleting handle '+handle+'.') LOGGER.debug('DELETE Request to '+url) head = self.__get_headers('DELETE') veri = self.__HTTPS_verify # Make request: resp = None if self.__authentication_method == self.__auth_methods['user_pw']: resp = self.__session.delete(url, headers=head, v...
= False return resp
def check_if_username_exists(self, username): ''' Check if the username handles exists. :param username: The username, in the form index:prefix/suffix :raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException` :raises: :exc:`~b2handle.handleexceptions.GenericHandleError` :return: True. If it does not exist, an ...
= b2handle.utilhandle.remove_index_from_handle(username) resp = self.send_handle_get_request(handle) resp_content = decoded_response(resp) if b2handle.hsresponses.does_handle_exist(resp): handlerecord_json = json.loads(resp_content) if not handlerecord_json['handle'] == handle: raise GenericHandleError( operation='Chec...
username exists went wrong' raise GenericHandleError(operation=op, handle=handle, response=resp, msg=msg)
def __get_headers(self, action): ''' Create HTTP headers for different HTTP requests. Content-type and Accept are 'application/json', as the library is interacting with a REST API. :param action: Action for which to create the header ('GET', 'PUT', 'DELETE', 'SEARCH'). :return: dict containing key-value pairs, e.g. 'Ac...
'GET': header['Accept'] = accept elif action is 'PUT' or action is 'DELETE': if self.__authentication_method == self.__auth_methods['cert']: header['Authorization'] = 'Handle clientCert="true"' elif self.__authentication_method == self.__auth_methods['user_pw']: header['Authorization'] = 'Basic ' + self.__basic_authent...
def make_handle_URL(self, handle, indices=None, overwrite=None, other_url=None): ''' Create the URL for a HTTP request (URL + query string) to request a specific handle from the Handle Server. :param handle: The handle to access. :param indices: Optional. A list of integers or strings. Indices of the handle record entr...
be appended to the URL ({?,&}overwrite=true or {?,&}overwrite=false). If not set, no flag is set, thus the Handle Server's default behaviour will be used. Defaults to None. :param other_url: Optional. If a different Handle Server URL than the one specified in the constructor should be used. Defaults to None. If set, it...
URL, e.g. 'http://some.handle.server/api/handles/prefix/suffix?index=2&index=6&overwrite=false ''' LOGGER.debug('make_handle_URL...') separator = '?' if other_url is not None: url = other_url else: url = self.__handle_server_url.strip('/') +'/'+\ self.__REST_API_url_extension.strip('/') url = url.strip('/')+'/'+ handle...
def publish_metric(self, metric_name, metric_value, epoch_seconds=None): '''Record a single hit on a given metric. Args: metric_name: The name of the metric to record with Carbon. metric_value: The value to record with Carbon. epoch_seconds: Optionally specify the time for the metric hit. Returns: None ''' if epoch_sec...
def register_repeating_metric(self, metric_name, frequency, getter): '''Record hits to a metric at a specified interval. Args: metric_name: The name of the metric to record with Carbon. frequency: The frequency with which to poll the getter and record the value with Carbon. getter: A function which takes no arguments a...
recording the metric. ''' l = task.LoopingCall(self._publish_repeating_metric, metric_name, getter) repeating_metric_handle = RepeatingMetricHandle(l, frequency) self._repeating_metric_handles.append(repeating_metric_handle) if self.running: repeating_metric_handle.start() return repeating_metric_handle
def setup(console=False, port=None, menu=True): """Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Arguments: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to connect with Pyblish QML, default provided by ...
Loaded successfully.")
def show(): """Try showing the most desirable GUI This function cycles through the currently registered graphical user interfaces, if any, and presents it to the user. """ parent = None current = QtWidgets.QApplication.activeWindow() while current: parent = current current = parent.parent() window = (_discover_gui() or...
def _nuke_set_zero_margins(widget_object): """Remove Nuke margins when docked UI .. _More info: https://gist.github.com/maty974/4739917 """ parentApp = QtWidgets.QApplication.allWidgets() parentWidgetList = [] for parent in parentApp: for child in parent.children(): if widget_object.__class__.__name__ == child.__class_...
def dock(window): """ Expecting a window to parent into a Nuke panel, that is dockable. """ # Deleting existing dock # There is a bug where existing docks are kept in-memory when closed via UI if self._dock: print("Deleting existing dock...") parent = self._dock dialog = None stacked_widget = None main_windows = [] # G...
if isinstance(parent, QtWidgets.QStackedWidget): stacked_widget = parent if isinstance(parent, QtWidgets.QMainWindow): main_windows.append(parent) parent = parent.parent() dialog.deleteLater() if len(main_windows) > 1: # Then it's a floating window if stacked_widget.count() == 1: # Then it's empty and we can close it, ...
panel_widget.layout().addWidget(window) _nuke_set_zero_margins(panel_widget) self._dock = panel_widget return self._dock
def remove_index_from_handle(handle_with_index): ''' Returns index and handle separately, in a tuple. :handle_with_index: The handle string with an index (e.g. 500:prefix/suffix) :return: index and handle as a tuple. ''' split = handle_with_index.split(':') if len(split) == 2: split[0] = int(split[0]) return split elif...
def check_handle_syntax(string): ''' Checks the syntax of a handle without an index (are prefix and suffix there, are there too many slashes?). :string: The handle without index, as string prefix/suffix. :raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError` :return: True. If it's not ok, exceptio...
'No slash' raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected) if len(arr[0]) == 0: msg = 'Empty prefix' raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected) if len(arr[1]) == 0: msg = 'Empty suffix' raise handleexceptions.HandleSyntaxError(ms...
def create_authentication_string(username, password): ''' Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string. ''' username_utf8 = username.encode('utf-8') userpw_utf8 = password.encode('utf-8') username_perc = quote(username_utf8) userp...
def make_request_log_message(**args): ''' Creates a string containing all relevant information about a request made to the Handle System, for logging purposes. :handle: The handle that the request is about. :url: The url the request is sent to. :headers: The headers sent along with the request. :verify: Boolean paramet...
which the request was sent. :payload: Optional. The payload sent with the request. :return: A formatted string. ''' mandatory_args = ['op', 'handle', 'url', 'headers', 'verify', 'resp'] optional_args = ['payload'] util.check_presence_of_mandatory_args(args, mandatory_args) util.add_missing_optional_args_with_value_none...
+= space+'RESPONSECODE: '+str(args['resp'].status_code) message += space+'RESPONSE:'+space+str(args['resp'].content) return message
def request_xml(url, auth=None): ''' Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML ''' try: r = requests.get(url, auth=auth, verify=False) return r.text.encode('utf-8') except BaseException: logger.error("Skipping %s (error parsing the XML)" % url) return
def _get_catalog_url(self, url): ''' Returns the appropriate catalog URL by replacing html with xml in some cases :param str url: URL to the catalog ''' u = urlparse.urlsplit(url) name, ext = os.path.splitext(u.path) if ext == ".html": u = urlparse.urlsplit(url.replace(".html", ".xml")) url = u.geturl() return url
def _yield_leaves(self, url, tree): ''' Yields a URL corresponding to a leaf dataset for each dataset described by the catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree ''' for leaf in tree.findall('.//{%s}dataset[@urlPath]' % INV_NS): # Subset by the skips name = leaf...