sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def bed_occupied(self): """ bed_occupied: None -> boolean Determines whether the bed is currently occupied by requesting data from the remote XBee and comparing the analog value with a threshold. """ # Receive samples from the remote device self._set_send_samples(True) while True: packet = self.hw.wait_read_frame() if 'adc-0' in packet['samples'][0]: # Stop receiving samples from the remote device self._set_send_samples(False) return packet['samples'][0]['adc-0'] > XBeeAlarm.DETECT_THRESH
bed_occupied: None -> boolean Determines whether the bed is currently occupied by requesting data from the remote XBee and comparing the analog value with a threshold.
entailment
def checksum(self): """ checksum: None -> single checksum byte checksum adds all bytes of the binary, unescaped data in the frame, saves the last byte of the result, and subtracts it from 0xFF. The final result is the checksum """ total = 0 # Add together all bytes for byte in self.data: total += byteToInt(byte) # Only keep the last byte total = total & 0xFF return intToByte(0xFF - total)
checksum: None -> single checksum byte checksum adds all bytes of the binary, unescaped data in the frame, saves the last byte of the result, and subtracts it from 0xFF. The final result is the checksum
entailment
def verify(self, chksum): """ verify: 1 byte -> boolean verify checksums the frame, adds the expected checksum, and determines whether the result is correct. The result should be 0xFF. """ total = 0 # Add together all bytes for byte in self.data: total += byteToInt(byte) # Add checksum too total += byteToInt(chksum) # Only keep low bits total &= 0xFF # Check result return total == 0xFF
verify: 1 byte -> boolean verify checksums the frame, adds the expected checksum, and determines whether the result is correct. The result should be 0xFF.
entailment
def output(self): """ output: None -> valid API frame (binary data) output will produce a valid API frame for transmission to an XBee module. """ # start is one byte long, length is two bytes # data is n bytes long (indicated by length) # chksum is one byte long data = self.len_bytes() + self.data + self.checksum() # Only run the escaoe process if it hasn't been already if self.escaped and len(self.raw_data) < 1: self.raw_data = APIFrame.escape(data) if self.escaped: data = self.raw_data # Never escape start byte return APIFrame.START_BYTE + data
output: None -> valid API frame (binary data) output will produce a valid API frame for transmission to an XBee module.
entailment
def escape(data): """ escape: byte string -> byte string When a 'special' byte is encountered in the given data string, it is preceded by an escape byte and XORed with 0x20. """ escaped_data = b"" for byte in data: if intToByte(byteToInt(byte)) in APIFrame.ESCAPE_BYTES: escaped_data += APIFrame.ESCAPE_BYTE escaped_data += intToByte(0x20 ^ byteToInt(byte)) else: escaped_data += intToByte(byteToInt(byte)) return escaped_data
escape: byte string -> byte string When a 'special' byte is encountered in the given data string, it is preceded by an escape byte and XORed with 0x20.
entailment
def fill(self, byte): """ fill: byte -> None Adds the given raw byte to this APIFrame. If this APIFrame is marked as escaped and this byte is an escape byte, the next byte in a call to fill() will be unescaped. """ if self._unescape_next_byte: byte = intToByte(byteToInt(byte) ^ 0x20) self._unescape_next_byte = False elif self.escaped and byte == APIFrame.ESCAPE_BYTE: self._unescape_next_byte = True return self.raw_data += intToByte(byteToInt(byte))
fill: byte -> None Adds the given raw byte to this APIFrame. If this APIFrame is marked as escaped and this byte is an escape byte, the next byte in a call to fill() will be unescaped.
entailment
def parse(self): """ parse: None -> None Given a valid API frame, parse extracts the data contained inside it and verifies it against its checksum """ if len(self.raw_data) < 3: ValueError("parse() may only be called on a frame containing at " "least 3 bytes of raw data (see fill())") # First two bytes are the length of the data raw_len = self.raw_data[1:3] # Unpack it data_len = struct.unpack("> h", raw_len)[0] # Read the data data = self.raw_data[3:3 + data_len] chksum = self.raw_data[-1] # Checksum check self.data = data if not self.verify(chksum): raise ValueError("Invalid checksum")
parse: None -> None Given a valid API frame, parse extracts the data contained inside it and verifies it against its checksum
entailment
def _parse_IS_at_response(self, packet_info): """ If the given packet is a successful remote AT response for an IS command, parse the parameter field as IO data. """ if packet_info['id'] in ('at_response', 'remote_at_response') and \ packet_info['command'].lower() == b'is' and \ packet_info['status'] == b'\x00': return self._parse_samples(packet_info['parameter']) else: return packet_info['parameter']
If the given packet is a successful remote AT response for an IS command, parse the parameter field as IO data.
entailment
def _parse_ND_at_response(self, packet_info): """ If the given packet is a successful AT response for an ND command, parse the parameter field. """ if packet_info['id'] == 'at_response' and \ packet_info['command'].lower() == b'nd' and \ packet_info['status'] == b'\x00': result = {} # Parse each field directly result['source_addr'] = packet_info['parameter'][0:2] result['source_addr_long'] = packet_info['parameter'][2:10] # Parse the null-terminated node identifier field null_terminator_index = 10 while packet_info['parameter'][null_terminator_index: null_terminator_index+1] != b'\x00': null_terminator_index += 1 # Parse each field thereafter directly result['node_identifier'] = \ packet_info['parameter'][10:null_terminator_index] result['parent_address'] = \ packet_info['parameter'][null_terminator_index+1: null_terminator_index+3] result['device_type'] = \ packet_info['parameter'][null_terminator_index+3: null_terminator_index+4] result['status'] = \ packet_info['parameter'][null_terminator_index+4: null_terminator_index+5] result['profile_id'] = \ packet_info['parameter'][null_terminator_index+5: null_terminator_index+7] result['manufacturer'] = \ packet_info['parameter'][null_terminator_index+7: null_terminator_index+9] # Simple check to ensure a good parse if null_terminator_index+9 != len(packet_info['parameter']): raise ValueError("Improper ND response length: expected {0}, " "read {1} bytes".format( len(packet_info['parameter']), null_terminator_index+9) ) return result else: return packet_info['parameter']
If the given packet is a successful AT response for an ND command, parse the parameter field.
entailment
def halt(self): """ halt: None -> None If this instance has a separate thread running, it will be halted. This method will wait until the thread has cleaned up before returning. """ if self._callback: self._thread_continue = False self._thread.join()
halt: None -> None If this instance has a separate thread running, it will be halted. This method will wait until the thread has cleaned up before returning.
entailment
def run(self): """ run: None -> None This method overrides threading.Thread.run() and is automatically called when an instance is created with threading enabled. """ while True: try: self._callback(self.wait_read_frame()) except ThreadQuitException: # Expected termintation of thread due to self.halt() break except Exception as e: # Unexpected thread quit. if self._error_callback: self._error_callback(e)
run: None -> None This method overrides threading.Thread.run() and is automatically called when an instance is created with threading enabled.
entailment
def wait_read_frame(self, timeout=None): """ wait_read_frame: None -> frame info dictionary wait_read_frame calls XBee._wait_for_frame() and waits until a valid frame appears on the serial port. Once it receives a frame, wait_read_frame attempts to parse the data contained within it and returns the resulting dictionary """ frame = self._wait_for_frame(timeout) return self._split_response(frame.data)
wait_read_frame: None -> frame info dictionary wait_read_frame calls XBee._wait_for_frame() and waits until a valid frame appears on the serial port. Once it receives a frame, wait_read_frame attempts to parse the data contained within it and returns the resulting dictionary
entailment
def _wait_for_frame(self, timeout=None): """ _wait_for_frame: None -> binary data _wait_for_frame will read from the serial port until a valid API frame arrives. It will then return the binary data contained within the frame. If this method is called as a separate thread and self.thread_continue is set to False, the thread will exit by raising a ThreadQuitException. """ frame = APIFrame(escaped=self._escaped) deadline = 0 if timeout is not None and timeout > 0: deadline = time.time() + timeout while True: if self._callback and not self._thread_continue: raise ThreadQuitException if self.serial.inWaiting() == 0: if deadline and time.time() > deadline: raise _TimeoutException time.sleep(.01) continue byte = self.serial.read() if byte != APIFrame.START_BYTE: continue # Save all following bytes, if they are not empty if len(byte) == 1: frame.fill(byte) while(frame.remaining_bytes() > 0): byte = self.serial.read() if len(byte) == 1: frame.fill(byte) try: # Try to parse and return result frame.parse() # Ignore empty frames if len(frame.data) == 0: frame = APIFrame() continue return frame except ValueError: # Bad frame, so restart frame = APIFrame(escaped=self._escaped)
_wait_for_frame: None -> binary data _wait_for_frame will read from the serial port until a valid API frame arrives. It will then return the binary data contained within the frame. If this method is called as a separate thread and self.thread_continue is set to False, the thread will exit by raising a ThreadQuitException.
entailment
def main(): """ Sends an API AT command to read the lower-order address bits from an XBee Series 1 and looks for a response """ try: # Open serial port ser = serial.Serial('/dev/ttyUSB0', 9600) # Create XBee Series 1 object xbee = XBee(ser) # Send AT packet xbee.send('at', frame_id='A', command='DH') # Wait for response response = xbee.wait_read_frame() print response # Send AT packet xbee.send('at', frame_id='B', command='DL') # Wait for response response = xbee.wait_read_frame() print response # Send AT packet xbee.send('at', frame_id='C', command='MY') # Wait for response response = xbee.wait_read_frame() print response # Send AT packet xbee.send('at', frame_id='D', command='CE') # Wait for response response = xbee.wait_read_frame() print response except KeyboardInterrupt: pass finally: ser.close()
Sends an API AT command to read the lower-order address bits from an XBee Series 1 and looks for a response
entailment
def halt(self): """ halt: None -> None Stop the event, and remove the FD from the loop handler """ if self._callback: self._running.clear() self._ioloop.remove_handler(self.serial.fd) if self._frame_future is not None: self._frame_future.set_result(None) self._frame_future = None
halt: None -> None Stop the event, and remove the FD from the loop handler
entailment
def process_frames(self): """ process_frames: None -> None Wait for a frame to become available, when resolved call the callback """ while self._running.is_set(): try: frame = yield self._get_frame() info = self._split_response(frame.data) if info is not None: self._callback(info) except Exception as e: # Unexpected quit. if self._error_callback: self._error_callback(e)
process_frames: None -> None Wait for a frame to become available, when resolved call the callback
entailment
def _process_input(self, data, events): """ _process_input: _process_input will be notified when there is data ready on the serial connection to be read. It will read and process the data into an API Frame and then either resolve a frame future, or push the frame into the queue of frames needing to be processed """ frame = APIFrame(escaped=self._escaped) byte = self.serial.read() if byte != APIFrame.START_BYTE: return # Save all following bytes, if they are not empty if len(byte) == 1: frame.fill(byte) while(frame.remaining_bytes() > 0): byte = self.serial.read() if len(byte) == 1: frame.fill(byte) try: # Try to parse and return result frame.parse() # Ignore empty frames if len(frame.data) == 0: return if self._frame_future is not None: self._frame_future.set_result(frame) self._frame_future = None else: self._frame_queue.append(frame) except ValueError: return
_process_input: _process_input will be notified when there is data ready on the serial connection to be read. It will read and process the data into an API Frame and then either resolve a frame future, or push the frame into the queue of frames needing to be processed
entailment
def do_serial(self, p): """Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8""" try: self.serial.port = p self.serial.open() print 'Opening serial port: %s' % p except Exception, e: print 'Unable to open serial port: %s' % p
Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8
entailment
def register(self, name, callback, filter): """ register: string, function: string, data -> None, function: data -> boolean -> None Register will save the given name, callback, and filter function for use when a packet arrives. When one arrives, the filter function will be called to determine whether to call its associated callback function. If the filter method returns true, the callback method will be called with its associated name string and the packet which triggered the call. """ if name in self.names: raise ValueError("A callback has already been registered with \ the name '%s'" % name) self.handlers.append({ 'name': name, 'callback': callback, 'filter': filter }) self.names.add(name)
register: string, function: string, data -> None, function: data -> boolean -> None Register will save the given name, callback, and filter function for use when a packet arrives. When one arrives, the filter function will be called to determine whether to call its associated callback function. If the filter method returns true, the callback method will be called with its associated name string and the packet which triggered the call.
entailment
def run(self, oneshot=False): """ run: boolean -> None run will read and dispatch any packet which arrives from the XBee device """ if not self.xbee: raise ValueError("Either a serial port or an XBee must be provided \ to __init__ to execute run()") while True: self.dispatch(self.xbee.wait_read_frame()) if oneshot: break
run: boolean -> None run will read and dispatch any packet which arrives from the XBee device
entailment
def dispatch(self, packet): """ dispatch: XBee data dict -> None When called, dispatch checks the given packet against each registered callback method and calls each callback whose filter function returns true. """ for handler in self.handlers: if handler['filter'](packet): # Call the handler method with its associated # name and the packet which passed its filter check handler['callback'](handler['name'], packet)
dispatch: XBee data dict -> None When called, dispatch checks the given packet against each registered callback method and calls each callback whose filter function returns true.
entailment
def byteToInt(byte): """ byte -> int Determines whether to use ord() or not to get a byte's value. """ if hasattr(byte, 'bit_length'): # This is already an int return byte return ord(byte) if hasattr(byte, 'encode') else byte[0]
byte -> int Determines whether to use ord() or not to get a byte's value.
entailment
def get_data(search_string, search_by='ip'): """ Download data from talosintelligence.com for the given IP Return tabbed data text """ r_details = requests.get('https://talosintelligence.com/sb_api/query_lookup', headers={ 'Referer':'https://talosintelligence.com/reputation_center/lookup?search=%s'%search_string, 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0' }, params = { 'query':'/api/v2/details/ip/', 'query_entry':search_string }).json() r_wscore = requests.get('https://talosintelligence.com/sb_api/remote_lookup', headers={ 'Referer':'https://talosintelligence.com/reputation_center/lookup?search=%s'%search_string, 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0' }, params = {'hostname':'SDS', 'query_string':'/score/wbrs/json?url=%s' % search_string}).json() r_talos_blacklist = requests.get('https://www.talosintelligence.com/sb_api/blacklist_lookup', headers={ 'Referer':'https://talosintelligence.com/reputation_center/lookup?search=%s'%search_string, 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0' }, params = {'query_type':'ipaddr', 'query_entry':search_string}).json() # would be nice to plot this values #r_volume = requests.get('https://talosintelligence.com/sb_api/query_lookup', # params = { # 'query':'/api/v2/volume/ip/', # 'query_entry':search_string # }).json() # No used for now #r_related_ips = requests.get('https://talosintelligence.com/sb_api/query_lookup', # params = { # 'query':'/api/v2/related_ips/ip/', # 'query_entry':search_string # }).json() talos_blacklisted = {'status':False} if 'classifications' in r_talos_blacklist['entry']: talos_blacklisted['status'] = True talos_blacklisted['classifications'] = ", ".join(r_talos_blacklist['entry']['classifications']) talos_blacklisted['first_seen'] = r_talos_blacklist['entry']['first_seen'] + "UTC" talos_blacklisted['expiration'] = r_talos_blacklist['entry']['expiration'] + "UTC" data = { 'address':search_string, 'hostname':r_details['hostname'] if 'hostname' in r_details else "nodata", 'volume_change':r_details['daychange'] if 'daychange' in r_details else "nodata", 'lastday_volume':r_details['daily_mag'] if 'daily_mag' in r_details else "nodata", 'month_volume':r_details['monthly_mag'] if 'monthly_mag' in r_details else "nodata", 'email_reputation':r_details['email_score_name'] if 'email_score_name' in r_details else "nodata", 'web_reputation':r_details['web_score_name'] if 'web_score_name' in r_details else "nodata", 'weighted_reputation_score':r_wscore['response'], 'talos_blacklisted':"Yes" if talos_blacklisted['status'] else "No" #'weighted_reputation_score':r_wscore[0]['response']['wbrs']['score'], #'volumes':zip(*r_volume['data']) } return data
Download data from talosintelligence.com for the given IP Return tabbed data text
entailment
def insert_into_channel(api_key, api_secret, channel_key, video_key, **kwargs): """ Function which inserts video into a channel/playlist. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param channel_key: <string> Key of the channel to which add a video. :param video_key: <string> Key of the video that should be added to the channel. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html :return: <dict> Dict which represents the JSON response. """ jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Inserting video into channel") try: response = jwplatform_client.channels.videos.create( channel_key=channel_key, video_key=video_key, **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error inserting {} into channel {}.\n{}".format(video_key, channel_key, e)) sys.exit(e.message) return response
Function which inserts video into a channel/playlist. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param channel_key: <string> Key of the channel to which add a video. :param video_key: <string> Key of the video that should be added to the channel. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html :return: <dict> Dict which represents the JSON response.
entailment
def list_conversions(api_key, api_secret, video_key, **kwargs): """ Function which retrieves a list of a video object's conversions. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/conversions/list.html :return: <dict> Dict which represents the JSON response. """ jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Querying for video conversions.") try: response = jwplatform_client.videos.conversions.list(video_key=video_key, **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error querying for video conversions.\n{}".format(e)) sys.exit(e.message) return response
Function which retrieves a list of a video object's conversions. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/conversions/list.html :return: <dict> Dict which represents the JSON response.
entailment
def _build_request(self, path, params=None): """Build API request""" _url = '{scheme}://{host}{port}/{version}{path}'.format( scheme=self._scheme, host=self._host, port=':{}'.format(self._port) if self._port != 80 else '', version=self._api_version, path=path) if params is not None: _params = params.copy() else: _params = dict() # Add required API parameters _params['api_nonce'] = str(random.randint(0, 999999999)).zfill(9) _params['api_timestamp'] = int(time.time()) _params['api_key'] = self.__key _params['api_format'] = 'json' _params['api_kit'] = 'py-{}{}'.format( __version__, '-{}'.format(self._agent) if self._agent else '') # Construct Signature Base String sbs = '&'.join(['{}={}'.format( quote((unicode(key).encode('utf-8')), safe='~'), quote((unicode(value).encode('utf-8')), safe='~') ) for key, value in sorted(_params.items())]) # Add signature to the _params dict _params['api_signature'] = hashlib.sha1( '{}{}'.format(sbs, self.__secret).encode('utf-8')).hexdigest() return _url, _params
Build API request
entailment
def create_video(api_key, api_secret, local_video_path, api_format='json', **kwargs): """ Function which creates new video object via singlefile upload method. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to media on local machine. :param api_format: <string> Acceptable values include 'py','xml','json',and 'php' :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html :return: """ # Setup API client jwplatform_client = jwplatform.Client(api_key, api_secret) # Make /videos/create API call logging.info("Registering new Video-Object") try: response = jwplatform_client.videos.create(upload_method='single', **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error creating a video\n{}".format(e)) logging.info(response) # Construct base url for upload upload_url = '{}://{}{}'.format( response['link']['protocol'], response['link']['address'], response['link']['path'] ) # Query parameters for the upload query_parameters = response['link']['query'] query_parameters['api_format'] = api_format with open(local_video_path, 'rb') as f: files = {'file': f} r = requests.post(upload_url, params=query_parameters, files=files) logging.info('uploading file {} to url {}'.format(local_video_path, r.url)) logging.info('upload response: {}'.format(r.text)) logging.info(r)
Function which creates new video object via singlefile upload method. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to media on local machine. :param api_format: <string> Acceptable values include 'py','xml','json',and 'php' :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html :return:
entailment
def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs): """ Function which allows to replace the content of an EXISTING video object. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to media on local machine. :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html :return: """ filename = os.path.basename(local_video_path) # Setup API client jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Updating Video") try: response = jwplatform_client.videos.update( video_key=video_key, upload_method='s3', update_file='True', **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error updating the video\n{}".format(e)) sys.exit(e.message) logging.info(response) # Construct base url for upload upload_url = '{}://{}{}'.format( response['link']['protocol'], response['link']['address'], response['link']['path'] ) # Query parameters for the upload query_parameters = response['link']['query'] # HTTP PUT upload using requests headers = {'Content-Disposition': 'attachment; filename="{}"'.format(filename)} with open(local_video_path, 'rb') as f: r = requests.put(upload_url, params=query_parameters, headers=headers, data=f) logging.info('uploading file {} to url {}'.format(local_video_path, r.url)) logging.info('upload response: {}'.format(r.text)) logging.info(r)
Function which allows to replace the content of an EXISTING video object. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to media on local machine. :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html :return:
entailment
def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs): """ Function which updates the thumbnail for an EXISTING video utilizing position parameter. This function is useful for selecting a new thumbnail from with the already existing video content. Instead of position parameter, user may opt to utilize thumbnail_index parameter. Please eee documentation for further information. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param position: <float> Represents seconds into the duration of a video, for thumbnail extraction. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html :return: <dict> Dict which represents the JSON response. """ jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Updating video thumbnail.") try: response = jwplatform_client.videos.thumbnails.update( video_key=video_key, position=position, # Parameter which specifies seconds into video to extract thumbnail from. **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error updating thumbnail.\n{}".format(e)) sys.exit(e.message) return response
Function which updates the thumbnail for an EXISTING video utilizing position parameter. This function is useful for selecting a new thumbnail from with the already existing video content. Instead of position parameter, user may opt to utilize thumbnail_index parameter. Please eee documentation for further information. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param position: <float> Represents seconds into the duration of a video, for thumbnail extraction. :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html :return: <dict> Dict which represents the JSON response.
entailment
def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json', **kwargs): """ Function which updates the thumbnail for a particular video object with a locally saved image. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param local_video_image_path: <string> Local system path to an image. :param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php' :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html :return: <dict> Dict which represents the JSON response. """ jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Updating video thumbnail.") try: response = jwplatform_client.videos.thumbnails.update( video_key=video_key, **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error updating thumbnail.\n{}".format(e)) sys.exit(e.message) logging.info(response) # Construct base url for upload upload_url = '{}://{}{}'.format( response['link']['protocol'], response['link']['address'], response['link']['path'] ) # Query parameters for the upload query_parameters = response['link']['query'] query_parameters['api_format'] = api_format with open(local_video_image_path, 'rb') as f: files = {'file': f} r = requests.post(upload_url, params=query_parameters, files=files) logging.info('uploading file {} to url {}'.format(local_video_image_path, r.url)) logging.info('upload response: {}'.format(r.text))
Function which updates the thumbnail for a particular video object with a locally saved image. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param local_video_image_path: <string> Local system path to an image. :param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php' :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html :return: <dict> Dict which represents the JSON response.
entailment
def run_upload(video_file_path): """ Configures all of the needed upload_parameters and sets up all information pertinent to the video to be uploaded. :param video_file_path: <str> the absolute path to the video file """ upload_parameters = { 'file_path': video_file_path, 'file_size': os.stat(video_file_path).st_size, 'file_name': os.path.basename(video_file_path) } try: # Setup API client jwplatform_client = Client(JW_API_KEY, JW_API_SECRET) # Make /videos/create API call with multipart parameter specified jwplatform_video_create_response = jwplatform_client.videos.create( upload_method='multipart', title=upload_parameters['file_name'] ) except JWPlatformError: logging.exception('An error occurred during the uploader setup. Check that your API keys are properly ' 'set up in your environment, and ensure that the video file path exists.') return # Construct base url for upload upload_parameters['upload_url'] = '{protocol}://{address}{path}'.format(**jwplatform_video_create_response['link']) logging.info('Upload URL to be used: {}'.format(upload_parameters['upload_url'])) upload_parameters['query_parameters'] = jwplatform_video_create_response['link']['query'] upload_parameters['query_parameters']['api_format'] = 'json' upload_parameters['headers'] = {'X-Session-ID': jwplatform_video_create_response['session_id']} # The chunk offset will be updated several times during the course of the upload upload_parameters['chunk_offset'] = 0 # Perform the multipart upload with open(upload_parameters['file_path'], 'rb') as file_to_upload: while True: chunk = file_to_upload.read(BYTES_TO_BUFFER) if len(chunk) <= 0: break try: upload_chunk(chunk, upload_parameters) # Log any exceptions that bubbled up except requests.exceptions.RequestException: logging.exception('Error posting data, stopping upload...') break
Configures all of the needed upload_parameters and sets up all information pertinent to the video to be uploaded. :param video_file_path: <str> the absolute path to the video file
entailment
def upload_chunk(chunk, upload_parameters): """ Handles the POST request needed to upload a single portion of the video file. Serves as a helper method for upload_by_multipart(). The offset used to determine where a chunk begins and ends is updated in the course of this method's execution. :param chunk: <byte[]> the raw bytes of data from the video file :param upload_parameters: <dict> a collection of all pieces of info needed to upload the video """ begin_chunk = upload_parameters['chunk_offset'] # The next chunk will begin at (begin_chunk + len(chunk)), so the -1 ensures that the ranges do not overlap end_chunk = begin_chunk + len(chunk) - 1 file_size = upload_parameters['file_size'] filename = upload_parameters['file_size'] logging.info("begin_chunk / end_chunk = {} / {}".format(begin_chunk, end_chunk)) upload_parameters['headers'].update( { 'X-Content-Range': 'bytes {}-{}/{}'.format(begin_chunk, end_chunk, file_size), 'Content-Disposition': 'attachment; filename="{}"'.format(filename), 'Content-Type': 'application/octet-stream', 'Content-Length': str((end_chunk - begin_chunk) + 1) } ) response = requests.post( upload_parameters['upload_url'], params=upload_parameters['query_parameters'], headers=upload_parameters['headers'], data=chunk ) response.raise_for_status() # As noted before, the next chunk begins at (begin_chunk + len(chunk)) upload_parameters['chunk_offset'] = begin_chunk + len(chunk)
Handles the POST request needed to upload a single portion of the video file. Serves as a helper method for upload_by_multipart(). The offset used to determine where a chunk begins and ends is updated in the course of this method's execution. :param chunk: <byte[]> the raw bytes of data from the video file :param upload_parameters: <dict> a collection of all pieces of info needed to upload the video
entailment
def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs): """ Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param path_to_csv: <string> Local system path to desired CSV. Default will be within current working directory. :param result_limit: <int> Number of video results returned in response. (Suggested to leave at default of 1000) :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/list.html :return: <dict> Dict which represents the JSON response. """ path_to_csv = path_to_csv or os.path.join(os.getcwd(), 'video_list.csv') timeout_in_seconds = 2 max_retries = 3 retries = 0 offset = 0 videos = list() jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Querying for video list.") while True: try: response = jwplatform_client.videos.list(result_limit=result_limit, result_offset=offset, **kwargs) except jwplatform.errors.JWPlatformRateLimitExceededError: logging.error("Encountered rate limiting error. Backing off on request time.") if retries == max_retries: raise jwplatform.errors.JWPlatformRateLimitExceededError() timeout_in_seconds *= timeout_in_seconds # Exponential back off for timeout in seconds. 2->4->8->etc.etc. retries += 1 time.sleep(timeout_in_seconds) continue except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error querying for videos list.\n{}".format(e)) raise e # Reset retry flow-control variables upon a non successful query (AKA not rate limited) retries = 0 timeout_in_seconds = 2 # Add all fetched video objects to our videos list. next_videos = response.get('videos', []) last_query_total = response.get('total', 0) videos.extend(next_videos) offset += len(next_videos) logging.info("Accumulated {} videos.".format(offset)) if offset >= last_query_total: # Condition which defines you've reached the end of the library break # Section for writing video library to csv desired_fields = ['key', 'title', 'description', 'tags', 'date', 'link'] should_write_header = not os.path.isfile(path_to_csv) with open(path_to_csv, 'a+') as path_to_csv: # Only write columns to the csv which are specified above. Columns not specified are ignored. writer = csv.DictWriter(path_to_csv, fieldnames=desired_fields, extrasaction='ignore') if should_write_header: writer.writeheader() writer.writerows(videos)
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param path_to_csv: <string> Local system path to desired CSV. Default will be within current working directory. :param result_limit: <int> Number of video results returned in response. (Suggested to leave at default of 1000) :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/list.html :return: <dict> Dict which represents the JSON response.
entailment
def create_channel(api_key, api_secret, channel_type='manual', **kwargs): """ Function which creates a new channel. Channels serve as containers of video/media objects. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param channel_type: <string> REQUIRED Acceptable values include 'manual','dynamic','trending','feed','search' :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/channels/create.html :return: <dict> Dict which represents the JSON response. """ jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Creating new channel with keyword args.") try: response = jwplatform_client.channels.create(type=channel_type, **kwargs) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error creating new channel.\n{}".format(e)) sys.exit(e.message) return response
Function which creates a new channel. Channels serve as containers of video/media objects. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param channel_type: <string> REQUIRED Acceptable values include 'manual','dynamic','trending','feed','search' :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/channels/create.html :return: <dict> Dict which represents the JSON response.
entailment
def update_custom_params(api_key, api_secret, video_key, params): """ Function which allows you to update a video's custom params. Custom params are indicated by key-values of "custom.<key>" = "<value>" so they must be provided as a dictionary and passed to the platform API call. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param params: Custom params in the format of a dictionary, e.g. >>> params = {'year': '2017', 'category': 'comedy'} >>> update_custom_params('XXXXXXXX', 'XXXXXXXXXXXXXXXXX', 'dfT6JSb2', params) :return: None """ formatted_params = {'custom.{}'.format(k): v for k,v in params.items()} # Setup API client jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Updating Video") try: response = jwplatform_client.videos.update( video_key=video_key, **formatted_params) except jwplatform.errors.JWPlatformError as e: logging.error("Encountered an error updating the video\n{}".format(e)) sys.exit(e.message) logging.info(response)
Function which allows you to update a video's custom params. Custom params are indicated by key-values of "custom.<key>" = "<value>" so they must be provided as a dictionary and passed to the platform API call. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard. :param params: Custom params in the format of a dictionary, e.g. >>> params = {'year': '2017', 'category': 'comedy'} >>> update_custom_params('XXXXXXXX', 'XXXXXXXXXXXXXXXXX', 'dfT6JSb2', params) :return: None
entailment
def image(self): r""" Tuple with a CAPTCHA text and a Image object. Images are generated on the fly, using given text source, TTF font and other parameters passable through __init__. All letters in used text are morphed. Also a line is morphed and pased onto CAPTCHA text. Additionaly, if self.noise > 1/255, a "snowy" image is merged with CAPTCHA image with a 50/50 ratio. Property returns a pair containing a string with text in returned image and image itself. :returns: ``tuple`` (CAPTCHA text, Image object) """ text = self.text w, h = self.font.getsize(text) margin_x = round(self.margin_x * w / self.w) margin_y = round(self.margin_y * h / self.h) image = Image.new('RGB', (w + 2*margin_x, h + 2*margin_y), (255, 255, 255)) # Text self._writeText(image, text, pos=(margin_x, margin_y)) # Line self._drawLine(image) # White noise noise = self._whiteNoise(image.size) if noise is not None: image = Image.blend(image, noise, 0.5) # Resize image = image.resize(self.size, resample=self.resample) return (text, image)
r""" Tuple with a CAPTCHA text and a Image object. Images are generated on the fly, using given text source, TTF font and other parameters passable through __init__. All letters in used text are morphed. Also a line is morphed and pased onto CAPTCHA text. Additionaly, if self.noise > 1/255, a "snowy" image is merged with CAPTCHA image with a 50/50 ratio. Property returns a pair containing a string with text in returned image and image itself. :returns: ``tuple`` (CAPTCHA text, Image object)
entailment
def bytes(self): r""" Tuple with a CAPTCHA text and a BytesIO object. Property calls self.image and saves image contents in a BytesIO instance, returning CAPTCHA text and BytesIO as a tuple. See: image. :returns: ``tuple`` (CAPTCHA text, BytesIO object) """ text, image = self.image bytes = BytesIO() image.save(bytes, format=self.format) bytes.seek(0) return (text, bytes)
r""" Tuple with a CAPTCHA text and a BytesIO object. Property calls self.image and saves image contents in a BytesIO instance, returning CAPTCHA text and BytesIO as a tuple. See: image. :returns: ``tuple`` (CAPTCHA text, BytesIO object)
entailment
def write(self, file): r""" Save CAPTCHA image in given filepath. Property calls self.image and saves image contents in a file, returning CAPTCHA text and filepath as a tuple. See: image. :param file: Path to file, where CAPTCHA image will be saved. :returns: ``tuple`` (CAPTCHA text, filepath) """ text, image = self.image image.save(file, format=self.format) return (text, file)
r""" Save CAPTCHA image in given filepath. Property calls self.image and saves image contents in a file, returning CAPTCHA text and filepath as a tuple. See: image. :param file: Path to file, where CAPTCHA image will be saved. :returns: ``tuple`` (CAPTCHA text, filepath)
entailment
def text(self): """Text received from self.source.""" if isinstance(self.source, str): return self.source else: return self.source()
Text received from self.source.
entailment
def _writeText(self, image, text, pos): """Write morphed text in Image object.""" offset = 0 x, y = pos for c in text: # Write letter c_size = self.font.getsize(c) c_image = Image.new('RGBA', c_size, (0, 0, 0, 0)) c_draw = ImageDraw.Draw(c_image) c_draw.text((0, 0), c, font=self.font, fill=(0, 0, 0, 255)) # Transform c_image = self._rndLetterTransform(c_image) # Paste onto image image.paste(c_image, (x+offset, y), c_image) offset += c_size[0]
Write morphed text in Image object.
entailment
def _drawLine(self, image): """Draw morphed line in Image object.""" w, h = image.size w *= 5 h *= 5 l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0)) l_draw = ImageDraw.Draw(l_image) x1 = int(w * random.uniform(0, 0.1)) y1 = int(h * random.uniform(0, 1)) x2 = int(w * random.uniform(0.9, 1)) y2 = int(h * random.uniform(0, 1)) # Line width modifier was chosen as an educated guess # based on default image area. l_width = round((w * h)**0.5 * 2.284e-2) # Draw l_draw.line(((x1, y1), (x2, y2)), fill=(0, 0, 0, 255), width=l_width) # Transform l_image = self._rndLineTransform(l_image) l_image = l_image.resize(image.size, resample=self.resample) # Paste onto image image.paste(l_image, (0, 0), l_image)
Draw morphed line in Image object.
entailment
def _whiteNoise(self, size): """Generate white noise and merge it with given Image object.""" if self.noise > 0.003921569: # 1./255. w, h = size pixel = (lambda noise: round(255 * random.uniform(1-noise, 1))) n_image = Image.new('RGB', size, (0, 0, 0, 0)) rnd_grid = map(lambda _: tuple([pixel(self.noise)]) * 3, [0] * w * h) n_image.putdata(list(rnd_grid)) return n_image else: return None
Generate white noise and merge it with given Image object.
entailment
def _rndLetterTransform(self, image): """Randomly morph a single character.""" w, h = image.size dx = w * random.uniform(0.2, 0.7) dy = h * random.uniform(0.2, 0.7) x1, y1 = self.__class__._rndPointDisposition(dx, dy) x2, y2 = self.__class__._rndPointDisposition(dx, dy) w += abs(x1) + abs(x2) h += abs(x1) + abs(x2) quad = self.__class__._quadPoints((w, h), (x1, y1), (x2, y2)) return image.transform(image.size, Image.QUAD, data=quad, resample=self.resample)
Randomly morph a single character.
entailment
def _rndPointDisposition(dx, dy): """Return random disposition point.""" x = int(random.uniform(-dx, dx)) y = int(random.uniform(-dy, dy)) return (x, y)
Return random disposition point.
entailment
def _quadPoints(size, disp1, disp2): """Return points for QUAD transformation.""" w, h = size x1, y1 = disp1 x2, y2 = disp2 return ( x1, -y1, -x1, h + y2, w + x2, h - y2, w - x2, y1 )
Return points for QUAD transformation.
entailment
def path_helper(self, operations, view, **kwargs): """Path helper that allows passing a bottle view function.""" operations.update(yaml_utils.load_operations_from_docstring(view.__doc__)) app = kwargs.get('app', _default_app) route = self._route_for_view(app, view) return self.bottle_path_to_openapi(route.rule)
Path helper that allows passing a bottle view function.
entailment
def path_helper(self, operations, view, app=None, **kwargs): """Path helper that allows passing a Flask view function.""" rule = self._rule_for_view(view, app=app) operations.update(yaml_utils.load_operations_from_docstring(view.__doc__)) if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView): for method in view.methods: if method in rule.methods: method_name = method.lower() method = getattr(view.view_class, method_name) operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__) return self.flaskpath2openapi(rule.rule)
Path helper that allows passing a Flask view function.
entailment
def _operations_from_methods(handler_class): """Generator of operations described in handler's http methods :param handler_class: :type handler_class: RequestHandler descendant """ for httpmethod in yaml_utils.PATH_KEYS: method = getattr(handler_class, httpmethod) operation_data = yaml_utils.load_yaml_from_docstring(method.__doc__) if operation_data: operation = {httpmethod: operation_data} yield operation
Generator of operations described in handler's http methods :param handler_class: :type handler_class: RequestHandler descendant
entailment
def tornadopath2openapi(urlspec, method): """Convert Tornado URLSpec to OpenAPI-compliant path. :param urlspec: :type urlspec: URLSpec :param method: Handler http method :type method: function """ if sys.version_info >= (3, 3): args = list(inspect.signature(method).parameters.keys())[1:] else: if getattr(method, '__tornado_coroutine__', False): method = method.__wrapped__ args = inspect.getargspec(method).args[1:] params = tuple('{{{}}}'.format(arg) for arg in args) try: path_tpl = urlspec.matcher._path except AttributeError: # tornado<4.5 path_tpl = urlspec._path path = (path_tpl % params) if path.count('/') > 1: path = path.rstrip('/?*') return path
Convert Tornado URLSpec to OpenAPI-compliant path. :param urlspec: :type urlspec: URLSpec :param method: Handler http method :type method: function
entailment
def path_helper(self, operations, urlspec, **kwargs): """Path helper that allows passing a Tornado URLSpec or tuple.""" if not isinstance(urlspec, URLSpec): urlspec = URLSpec(*urlspec) for operation in self._operations_from_methods(urlspec.handler_class): operations.update(operation) if not operations: raise APISpecError( 'Could not find endpoint for urlspec {0}'.format(urlspec), ) params_method = getattr(urlspec.handler_class, list(operations.keys())[0]) operations.update(self._extensions_from_handler(urlspec.handler_class)) return self.tornadopath2openapi(urlspec, params_method)
Path helper that allows passing a Tornado URLSpec or tuple.
entailment
def generate_mfa_token(self, user_id, expires_in=259200, reusable=False): """ Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period. For example, use this token for account recovery. :param user_id: Id of the user :type user_id: int :param expires_in: Set the duration of the token in seconds. (default: 259200 seconds = 72h) 72 hours is the max value. :type expires_in: int :param reusable: Defines if the token reusable. (default: false) If set to true, token can be used for multiple apps, until it expires. :type reusable: bool Returns a mfa token :return: return the object if success :rtype: MFAToken See https://developers.onelogin.com/api-docs/1/multi-factor-authentication/generate-mfa-token Generate MFA Token documentation """ self.clean_error() try: url = self.get_url(Constants.GENERATE_MFA_TOKEN_URL, user_id) data = { 'expires_in': expires_in, 'reusable': reusable } response = self.execute_call('post', url, json=data) if response.status_code == 201: json_data = response.json() if json_data: return MFAToken(json_data) else: self.error = self.extract_status_code_from_response(response) self.error_description = self.extract_error_message_from_response(response) except Exception as e: self.error = 500 self.error_description = e.args[0]
Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period. For example, use this token for account recovery. :param user_id: Id of the user :type user_id: int :param expires_in: Set the duration of the token in seconds. (default: 259200 seconds = 72h) 72 hours is the max value. :type expires_in: int :param reusable: Defines if the token reusable. (default: false) If set to true, token can be used for multiple apps, until it expires. :type reusable: bool Returns a mfa token :return: return the object if success :rtype: MFAToken See https://developers.onelogin.com/api-docs/1/multi-factor-authentication/generate-mfa-token Generate MFA Token documentation
entailment
def camel_to_snake(camel): """Convert camelCase to snake_case.""" ret = [] last_lower = False for char in camel: current_upper = char.upper() == char if current_upper and last_lower: ret.append("_") ret.append(char.lower()) else: ret.append(char.lower()) last_lower = not current_upper return "".join(ret)
Convert camelCase to snake_case.
entailment
def register_id(self, id_string): """Register a manually assigned id as used, to avoid collisions. """ try: prefix, count = id_string.rsplit("_", 1) count = int(count) except ValueError: # We don't need to worry about ids that don't match our pattern pass else: if prefix == self.prefix: self.counter = max(count, self.counter)
Register a manually assigned id as used, to avoid collisions.
entailment
def parse(cls, root): """ Create a new AMDSec by parsing root. :param root: Element or ElementTree to be parsed into an object. """ if root.tag != utils.lxmlns("mets") + "amdSec": raise exceptions.ParseError( "AMDSec can only parse amdSec elements with METS namespace." ) section_id = root.get("ID") subsections = [] for child in root: subsection = SubSection.parse(child) subsections.append(subsection) return cls(section_id, subsections)
Create a new AMDSec by parsing root. :param root: Element or ElementTree to be parsed into an object.
entailment
def serialize(self, now=None): """ Serialize this amdSec and all children to lxml Element and return it. :param str now: Default value for CREATED in children if none set :return: amdSec Element with all children """ if self._tree is not None: return self._tree el = etree.Element(utils.lxmlns("mets") + self.tag, ID=self.id_string) self.subsections.sort() for child in self.subsections: el.append(child.serialize(now)) return el
Serialize this amdSec and all children to lxml Element and return it. :param str now: Default value for CREATED in children if none set :return: amdSec Element with all children
entailment
def parse(cls, element): """ Create a new AltRecordID by parsing root. :param element: Element to be parsed into an AltRecordID. :raises exceptions.ParseError: If element is not a valid altRecordID. """ if element.tag != cls.ALT_RECORD_ID_TAG: raise exceptions.ParseError( u"AltRecordID got unexpected tag {}; expected {}".format( element.tag, cls.ALT_RECORD_ID_TAG ) ) return cls(element.text, id=element.get(u"ID"), type=element.get(u"TYPE"))
Create a new AltRecordID by parsing root. :param element: Element to be parsed into an AltRecordID. :raises exceptions.ParseError: If element is not a valid altRecordID.
entailment
def parse(cls, element): """ Create a new Agent by parsing root. :param element: Element to be parsed into an Agent. :raises exceptions.ParseError: If element is not a valid agent. """ if element.tag != cls.AGENT_TAG: raise exceptions.ParseError( u"Agent got unexpected tag {}; expected {}".format( element.tag, cls.AGENT_TAG ) ) role = element.get(u"ROLE") if not role: raise exceptions.ParseError(u"Agent must have a ROLE attribute.") if role == u"OTHER": role = element.get(u"OTHERROLE") or role agent_type = element.get(u"TYPE") if agent_type == u"OTHER": agent_type = element.get(u"OTHERTYPE") or agent_type agent_id = element.get(u"ID") try: name = element.find(cls.NAME_TAG).text except AttributeError: name = None notes = [note.text for note in element.findall(cls.NOTE_TAG)] return cls(role, id=agent_id, type=agent_type, name=name, notes=notes)
Create a new Agent by parsing root. :param element: Element to be parsed into an Agent. :raises exceptions.ParseError: If element is not a valid agent.
entailment
def get_status(self): """ Returns the STATUS when serializing. Calculates based on the subsection type and if it's replacing anything. :returns: None or the STATUS string. """ if self.status is not None: return self.status if self.subsection == "dmdSec": if self.older is None: return "original" else: return "updated" if self.subsection in ("techMD", "rightsMD"): # TODO how to handle ones where newer has been deleted? if self.newer is None: return "current" else: return "superseded" return None
Returns the STATUS when serializing. Calculates based on the subsection type and if it's replacing anything. :returns: None or the STATUS string.
entailment
def replace_with(self, new_subsection): """ Replace this SubSection with new_subsection. Replacing SubSection must be the same time. That is, you can only replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc. :param new_subsection: Updated version of this SubSection :type new_subsection: :class:`SubSection` """ if self.subsection != new_subsection.subsection: raise exceptions.MetsError( "Must replace a SubSection with one of the same type." ) # TODO convert this to a DB so have bidirectonal foreign keys?? self.newer = new_subsection new_subsection.older = self self.status = None
Replace this SubSection with new_subsection. Replacing SubSection must be the same time. That is, you can only replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc. :param new_subsection: Updated version of this SubSection :type new_subsection: :class:`SubSection`
entailment
def parse(cls, root): """ Create a new SubSection by parsing root. :param root: Element or ElementTree to be parsed into an object. :raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`. :raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap. """ subsection = root.tag.replace(utils.lxmlns("mets"), "", 1) if subsection not in cls.ALLOWED_SUBSECTIONS: raise exceptions.ParseError( "SubSection can only parse elements with tag in %s with METS namespace" % (cls.ALLOWED_SUBSECTIONS,) ) section_id = root.get("ID") created = root.get("CREATED", "") status = root.get("STATUS", "") child = root[0] if child.tag == utils.lxmlns("mets") + "mdWrap": mdwrap = MDWrap.parse(child) obj = cls(subsection, mdwrap, section_id) elif child.tag == utils.lxmlns("mets") + "mdRef": mdref = MDRef.parse(child) obj = cls(subsection, mdref, section_id) else: raise exceptions.ParseError( "Child of %s must be mdWrap or mdRef" % subsection ) obj.created = created obj.status = status return obj
Create a new SubSection by parsing root. :param root: Element or ElementTree to be parsed into an object. :raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`. :raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap.
entailment
def serialize(self, now=None): """ Serialize this SubSection and all children to lxml Element and return it. :param str now: Default value for CREATED if none set :return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children """ created = self.created if self.created is not None else now el = etree.Element(utils.lxmlns("mets") + self.subsection, ID=self.id_string) if created: # Don't add CREATED if none was parsed el.set("CREATED", created) status = self.get_status() if status: el.set("STATUS", status) if self.contents: el.append(self.contents.serialize()) return el
Serialize this SubSection and all children to lxml Element and return it. :param str now: Default value for CREATED if none set :return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children
entailment
def parse(cls, root): """ Create a new MDWrap by parsing root. :param root: Element or ElementTree to be parsed into a MDWrap. """ if root.tag != utils.lxmlns("mets") + "mdRef": raise exceptions.ParseError( "MDRef can only parse mdRef elements with METS namespace." ) # Required attributes mdtype = root.get("MDTYPE") if not mdtype: raise exceptions.ParseError("mdRef must have a MDTYPE") target = root.get(utils.lxmlns("xlink") + "href") if not target: raise exceptions.ParseError("mdRef must have an xlink:href.") try: target = utils.urldecode(target) except ValueError: raise exceptions.ParseError( 'Value "{}" (of attribute xlink:href) is not a valid' " URL.".format(target) ) loctype = root.get("LOCTYPE") if not loctype: raise exceptions.ParseError("mdRef must have a LOCTYPE") # Optional attributes label = root.get("LABEL") otherloctype = root.get("OTHERLOCTYPE") return cls(target, mdtype, loctype, label, otherloctype)
Create a new MDWrap by parsing root. :param root: Element or ElementTree to be parsed into a MDWrap.
entailment
def parse(cls, root): """ Create a new MDWrap by parsing root. :param root: Element or ElementTree to be parsed into a MDWrap. :raises exceptions.ParseError: If mdWrap does not contain MDTYPE :raises exceptions.ParseError: If xmlData contains no children """ if root.tag != utils.lxmlns("mets") + "mdWrap": raise exceptions.ParseError( "MDWrap can only parse mdWrap elements with METS namespace." ) mdtype = root.get("MDTYPE") if not mdtype: raise exceptions.ParseError("mdWrap must have a MDTYPE") othermdtype = root.get("OTHERMDTYPE") document = root.xpath("mets:xmlData/*", namespaces=utils.NAMESPACES) if len(document) == 0: raise exceptions.ParseError( "All mdWrap/xmlData elements must have at least one child; this" " one has none" ) elif len(document) == 1: document = document[0] # Create a copy, so that the element is not moved by duplicate references. document = copy.deepcopy(document) return cls(document, mdtype, othermdtype)
Create a new MDWrap by parsing root. :param root: Element or ElementTree to be parsed into a MDWrap. :raises exceptions.ParseError: If mdWrap does not contain MDTYPE :raises exceptions.ParseError: If xmlData contains no children
entailment
def _data_to_lxml_el(data, ns, nsmap, element_maker=None, snake=True): """Convert tuple/list ``data`` to an ``lxml.etree._Element`` instance. :param tuple/list data: iterable whose first element is the snake-case string which is the name of the root XML element. Subsequent elements may be dicts (which encode XML attributes), tuples/lists (which encode sub-elements), or scalars (strings, ints or floats, which encode text under the element). :param str ns: the implicit namespace of all elements in the XML. :param dict nsmap: a dict of XML namespaces to define in the root element. :param ElementMaker element_maker: instance for creating XML elements. :returns: an ``lxml.etree._Element`` instance """ if not element_maker: element_maker = ElementMaker(namespace=nsmap[ns], nsmap=nsmap) tag = data[0] if snake: camel_tag = utils.snake_to_camel(tag) func = getattr(element_maker, camel_tag) args = [] attributes = {} for element in data[1:]: if isinstance(element, dict): for key, val in element.items(): attributes[key] = val elif isinstance(element, (tuple, list)): args.append( _data_to_lxml_el( element, ns, nsmap, element_maker=element_maker, snake=snake ) ) elif isinstance(element, six.text_type): args.append(element) elif isinstance(element, etree._Element): args.append(element) else: args.append(six.binary_type(element)) ret = func(*args) for attr, val in attributes.items(): try: ns, attr = attr.split(":") except ValueError: ns = None if snake: attr = utils.snake_to_camel(attr) if ns: attr = "{" + nsmap[ns] + "}" + attr ret.attrib[attr] = val else: ret.attrib[attr] = val return ret
Convert tuple/list ``data`` to an ``lxml.etree._Element`` instance. :param tuple/list data: iterable whose first element is the snake-case string which is the name of the root XML element. Subsequent elements may be dicts (which encode XML attributes), tuples/lists (which encode sub-elements), or scalars (strings, ints or floats, which encode text under the element). :param str ns: the implicit namespace of all elements in the XML. :param dict nsmap: a dict of XML namespaces to define in the root element. :param ElementMaker element_maker: instance for creating XML elements. :returns: an ``lxml.etree._Element`` instance
entailment
def _to_colon_ns(bracket_ns, default_ns=None, nsmap=None, snake=True): """Convert a namespaced tag/attribute name from explicit XML "bracket" notation to a more succinct Pythonic colon-separated notation using snake_case, e.g.,:: >>> _to_colon_ns( '{info:lc/xmlns/premis-v2}objectIdentifier', 'premis', utils.NAMESPACES) 'object_identifier' >>> _to_colon_ns('{info:lc/xmlns/premis-v2}objectIdentifier') 'premis:object_identifier' >>> _to_colon_ns( 'http://www.w3.org/2001/XMLSchema-instance}schemaLocation') 'xsi:schema_location' """ parts = [x.strip("{") for x in bracket_ns.split("}")] if len(parts) != 2: return bracket_ns ns, var = parts if default_ns and nsmap: try: ns = [k for k, v in nsmap.items() if v == ns][0] if ns == default_ns: if snake: return utils.camel_to_snake(var) return var except IndexError: pass if snake: return ":".join([ns, utils.camel_to_snake(var)]) return ":".join([ns, var])
Convert a namespaced tag/attribute name from explicit XML "bracket" notation to a more succinct Pythonic colon-separated notation using snake_case, e.g.,:: >>> _to_colon_ns( '{info:lc/xmlns/premis-v2}objectIdentifier', 'premis', utils.NAMESPACES) 'object_identifier' >>> _to_colon_ns('{info:lc/xmlns/premis-v2}objectIdentifier') 'premis:object_identifier' >>> _to_colon_ns( 'http://www.w3.org/2001/XMLSchema-instance}schemaLocation') 'xsi:schema_location'
entailment
def _get_el_attributes(lxml_el, ns=None, nsmap=None): """Return the XML attributes of lxml ``Element`` instance lxml_el as a dict where namespaced attributes are represented via colon-delimiting and using snake case. """ attrs = {} for attr, val in lxml_el.items(): attr = _to_colon_ns(attr, default_ns=ns, nsmap=nsmap) attrs[attr] = val return attrs
Return the XML attributes of lxml ``Element`` instance lxml_el as a dict where namespaced attributes are represented via colon-delimiting and using snake case.
entailment
def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True): """Convert an ``lxml._Element`` instance to a Python tuple.""" tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap) ret = [tag_name] attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap) if attributes: ret.append(attributes) for sub_el in lxml_el: ret.append(_lxml_el_to_data(sub_el, ns, nsmap, snake=snake)) text = lxml_el.text if text: ret.append(text) return tuple(ret)
Convert an ``lxml._Element`` instance to a Python tuple.
entailment
def data_to_premis(data, premis_version=utils.PREMIS_VERSION): """Given tuple ``data`` representing a PREMIS entity (object, event or agent), return an ``lxml.etree._Element`` instance. E.g.,:: >>> p = data_to_premis(( 'event', utils.PREMIS_META, ( 'event_identifier', ('event_identifier_type', 'UUID'), ('event_identifier_value', str(uuid4())) ) )) >>> etree.tostring(p, pretty_print=True).decode('utf8') '''<premis:event xmlns:premis="info:lc/xmlns/premis-v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2" xsi:schemaLocation="info:lc/xmlns/premis-v2 http://www.loc.gov/standards/premis/v2/premis-v2-2.xsd"> <premis:eventIdentifier> <premis:eventIdentifierType>UUID</premis:eventIdentifierType> <premis:eventIdentifierValue>f4b7758f-e7b2-4155-9b56-d76965849fc1</premis:eventIdentifierValue> </premis:eventIdentifier> </premis:event>''' """ nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"] return _data_to_lxml_el(data, "premis", nsmap)
Given tuple ``data`` representing a PREMIS entity (object, event or agent), return an ``lxml.etree._Element`` instance. E.g.,:: >>> p = data_to_premis(( 'event', utils.PREMIS_META, ( 'event_identifier', ('event_identifier_type', 'UUID'), ('event_identifier_value', str(uuid4())) ) )) >>> etree.tostring(p, pretty_print=True).decode('utf8') '''<premis:event xmlns:premis="info:lc/xmlns/premis-v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2" xsi:schemaLocation="info:lc/xmlns/premis-v2 http://www.loc.gov/standards/premis/v2/premis-v2-2.xsd"> <premis:eventIdentifier> <premis:eventIdentifierType>UUID</premis:eventIdentifierType> <premis:eventIdentifierValue>f4b7758f-e7b2-4155-9b56-d76965849fc1</premis:eventIdentifierValue> </premis:eventIdentifier> </premis:event>'''
entailment
def premis_to_data(premis_lxml_el): """Transform a PREMIS ``lxml._Element`` instance to a Python tuple.""" premis_version = premis_lxml_el.get("version", utils.PREMIS_VERSION) nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"] return _lxml_el_to_data(premis_lxml_el, "premis", nsmap)
Transform a PREMIS ``lxml._Element`` instance to a Python tuple.
entailment
def data_find(data, path): """Find and return the first element-as-tuple in tuple ``data`` using simplified XPath ``path``. """ path_parts = path.split("/") try: sub_elm = [ el for el in data if isinstance(el, (tuple, list)) and el[0] == path_parts[0] ][0] except IndexError: return None else: if len(path_parts) > 1: return data_find(sub_elm, "/".join(path_parts[1:])) return sub_elm
Find and return the first element-as-tuple in tuple ``data`` using simplified XPath ``path``.
entailment
def tuple_to_schema(tuple_): """Convert a tuple representing an XML data structure into a schema tuple that can be used in the ``.schema`` property of a sub-class of PREMISElement. """ schema = [] for element in tuple_: if isinstance(element, (tuple, list)): try: if isinstance(element[1], six.string_types): schema.append((element[0],)) else: schema.append(tuple_to_schema(element)) except IndexError: schema.append((element[0],)) else: schema.append(element) return tuple(schema)
Convert a tuple representing an XML data structure into a schema tuple that can be used in the ``.schema`` property of a sub-class of PREMISElement.
entailment
def generate_element_class(tuple_instance): """Dynamically create a sub-class of PREMISElement given ``tuple_instance``, which is a tuple representing an XML data structure. """ schema = tuple_to_schema(tuple_instance) def defaults(self): return {} def schema_getter(self): return schema new_class_name = "PREMIS{}Element".format(schema[0].capitalize()) return type( new_class_name, (PREMISElement,), {"defaults": property(defaults), "schema": property(schema_getter)}, )
Dynamically create a sub-class of PREMISElement given ``tuple_instance``, which is a tuple representing an XML data structure.
entailment
def data_find_all(data, path, dyn_cls=False): """Find and return all element-as-tuples in tuple ``data`` using simplified XPath ``path``. """ path_parts = path.split("/") try: sub_elms = tuple( el for el in data if isinstance(el, (tuple, list)) and el[0] == path_parts[0] ) except IndexError: return None if len(path_parts) > 1: ret = [] for sub_elm in sub_elms: for x in data_find_all(sub_elm, "/".join(path_parts[1:])): ret.append(x) ret = tuple(ret) else: ret = sub_elms if ret and dyn_cls: cls = generate_element_class(ret[0]) return tuple(cls(data=tuple_) for tuple_ in ret) return ret
Find and return all element-as-tuples in tuple ``data`` using simplified XPath ``path``.
entailment
def data_find_text(data, path): """Return the text value of the element-as-tuple in tuple ``data`` using simplified XPath ``path``. """ el = data_find(data, path) if not isinstance(el, (list, tuple)): return None texts = [child for child in el[1:] if not isinstance(child, (tuple, list, dict))] if not texts: return None return " ".join( [ # How should we deal with decoding errors when `x` is binary? # For now, we're using the ``strict`` mode. Other options here: # https://docs.python.org/3/library/functions.html#open. six.ensure_text(x, encoding="utf-8", errors="strict") for x in texts ] )
Return the text value of the element-as-tuple in tuple ``data`` using simplified XPath ``path``.
entailment
def _generate_data(schema, elements, attributes=None, path=None): """Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data`` representing a PREMIS XML element, where the values in dict ``elements`` and the values in dict ``attributes`` are located in the appropriate locations in the ``data`` tree structure. """ path = path or [] attributes = attributes or {} tag_name = schema[0] data = [tag_name] if attributes: data.append(attributes) new_path = path[:] new_path.append(tag_name) root = new_path[0] possible_paths = ["__".join(new_path), tag_name] if root != tag_name and tag_name.startswith(root): possible_paths.append(tag_name.lstrip(root)[1:]) for possible_path in possible_paths: val = elements.get(possible_path) if val: if isinstance(val, (tuple, list)): data = tuple(val) else: if attributes: data = (tag_name, attributes, val) else: data = (tag_name, val) return tuple(data) for subschema in schema[1:]: subel = _generate_data(subschema, elements, path=new_path) if (not subel) or (subel == subschema): continue if all(map(lambda x: isinstance(x, tuple), subel)): for subsubel in subel: data.append(subsubel) elif not el_is_empty(subel): data.append(subel) return tuple(data)
Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data`` representing a PREMIS XML element, where the values in dict ``elements`` and the values in dict ``attributes`` are located in the appropriate locations in the ``data`` tree structure.
entailment
def el_is_empty(el): """Return ``True`` if tuple ``el`` represents an empty XML element.""" if len(el) == 1 and not isinstance(el[0], (list, tuple)): return True subels_are_empty = [] for subel in el: if isinstance(subel, (list, tuple)): subels_are_empty.append(el_is_empty(subel)) else: subels_are_empty.append(not bool(subel)) return all(subels_are_empty)
Return ``True`` if tuple ``el`` represents an empty XML element.
entailment
def get_attrs_to_paths(schema, attrs_to_paths=None, path=None): """Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps attribute names to the simplified XPaths needed to retrieve them, e.g.,:: >>> {'object_identifier_type': 'object_identifier/object_identifier_type', 'object_identifier_value': 'object_identifier/object_identifier_value'} """ attrs_to_paths = attrs_to_paths or {} tag = schema[0] if len(schema) == 1: _insert_attr_path(attrs_to_paths, tag, "/".join(path + [tag])) else: for elem in schema[1:]: if isinstance(elem, dict): continue new_path = [] if path is None else path + [tag] if isinstance(elem, (list, tuple)): attrs_to_paths.update( get_attrs_to_paths( elem, attrs_to_paths=attrs_to_paths, path=new_path ) ) else: _insert_attr_path(attrs_to_paths, tag, "/".join(new_path)) return attrs_to_paths
Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps attribute names to the simplified XPaths needed to retrieve them, e.g.,:: >>> {'object_identifier_type': 'object_identifier/object_identifier_type', 'object_identifier_value': 'object_identifier/object_identifier_value'}
entailment
def _premis_version_from_data(data): """Given tuple ``data`` encoding a PREMIS element, attempt to return the PREMIS version it is using. If none can be found, return the default PREMIS version. """ for child in data: if isinstance(child, dict): version = child.get("version") if version: return version return utils.PREMIS_VERSION
Given tuple ``data`` encoding a PREMIS element, attempt to return the PREMIS version it is using. If none can be found, return the default PREMIS version.
entailment
def parsed_event_detail(self): """Parse and return our PREMIS eventDetail string value like:: 'program="7z"; version="9.20"; algorithm="bzip2"' and return a dict like:: {'algorithm': 'bzip2', 'version': '9.20', 'program': '7z'} """ attr = ( "event_detail_information__event_detail" if self.premis_version == utils.PREMIS_3_0_VERSION else "event_detail" ) return dict( [ tuple([x.strip(' "') for x in kv.strip().split("=", 1)]) for kv in getattr(self, attr).split(";") ] )
Parse and return our PREMIS eventDetail string value like:: 'program="7z"; version="9.20"; algorithm="bzip2"' and return a dict like:: {'algorithm': 'bzip2', 'version': '9.20', 'program': '7z'}
entailment
def compression_details(self): """Return as a 3-tuple, this PREMIS compression event's program, version, and algorithm used to perform the compression. """ event_type = self.findtext("event_type") if event_type != "compression": raise AttributeError( 'PREMIS events of type "{}" have no compression' " details".format(event_type) ) parsed_compression_event_detail = self.parsed_event_detail compression_program = _get_event_detail_attr( "program", parsed_compression_event_detail ) compression_algorithm = _get_event_detail_attr( "algorithm", parsed_compression_event_detail ) compression_program_version = _get_event_detail_attr( "version", parsed_compression_event_detail ) archive_tool = {"7z": "7-Zip"}.get(compression_program, compression_program) return compression_algorithm, compression_program_version, archive_tool
Return as a 3-tuple, this PREMIS compression event's program, version, and algorithm used to perform the compression.
entailment
def get_decompression_transform_files(self, offset=0): """Returns a list of dicts representing ``<mets:transformFile>`` elements with ``TRANSFORMTYPE="decompression"`` given ``compression_algorithm`` which is a comma-separated string of algorithms that must be used in the order provided to decompress the package, e.g., 'bzip2,tar' or 'lzma'. """ compression_algorithm, _, _ = self.compression_details return [ { "algorithm": algorithm, "order": str(index + offset + 1), "type": "decompression", } for index, algorithm in enumerate(compression_algorithm.split(",")) ]
Returns a list of dicts representing ``<mets:transformFile>`` elements with ``TRANSFORMTYPE="decompression"`` given ``compression_algorithm`` which is a comma-separated string of algorithms that must be used in the order provided to decompress the package, e.g., 'bzip2,tar' or 'lzma'.
entailment
def encryption_details(self): """Return as a 3-tuple, this PREMIS encryption event's program, version, and key used to perform the encryption. """ event_type = self.findtext("event_type") if event_type != "encryption": raise AttributeError( 'PREMIS events of type "{}" have no encryption' " details".format(event_type) ) parsed_encryption_event_detail = self.parsed_event_detail encryption_program = _get_event_detail_attr( "program", parsed_encryption_event_detail ) encryption_program_version = _get_event_detail_attr( "version", parsed_encryption_event_detail ) encryption_key = _get_event_detail_attr("key", parsed_encryption_event_detail) return encryption_program, encryption_program_version, encryption_key
Return as a 3-tuple, this PREMIS encryption event's program, version, and key used to perform the encryption.
entailment
def has_class_methods(*class_method_names): """Return a test function that, when given a class, returns ``True`` if that class has all of the class methods in ``class_method_names``. If an object is passed to the test function, check for the class methods on its class. """ def test(cls): if not isinstance(cls, type): cls = type(cls) for class_method_name in class_method_names: try: class_method = getattr(cls, class_method_name) if class_method.__self__ is not cls: return False except AttributeError: return False return True return test
Return a test function that, when given a class, returns ``True`` if that class has all of the class methods in ``class_method_names``. If an object is passed to the test function, check for the class methods on its class.
entailment
def has_methods(*method_names): """Return a test function that, when given an object (class or an instance), returns ``True`` if that object has all of the (regular) methods in ``method_names``. Note: this is testing for regular methods only and the test function will correctly return ``False`` if an instance has one of the specified methods as a classmethod or a staticmethod. However, it will incorrectly return ``True`` (false positives) for classmethods and staticmethods on a *class*. """ def test(obj): for method_name in method_names: try: method = getattr(obj, method_name) except AttributeError: return False else: if not callable(method): return False if not isinstance(obj, type): try: # An instance method is a method type with a __self__ # attribute that references the instance. if method.__self__ is not obj: return False except AttributeError: return False return True return test
Return a test function that, when given an object (class or an instance), returns ``True`` if that object has all of the (regular) methods in ``method_names``. Note: this is testing for regular methods only and the test function will correctly return ``False`` if an instance has one of the specified methods as a classmethod or a staticmethod. However, it will incorrectly return ``True`` (false positives) for classmethods and staticmethods on a *class*.
entailment
def provide(self, feature_name, provider, *args, **kwargs): """Provide a feature named ``feature_name`` using the provider object ``provider`` and any arguments (``args``, ``kwargs``) needed by the provider if it is callable. """ if not self.allow_replace: assert feature_name not in self.providers, "Duplicate feature: {!r}".format( feature_name ) if callable(provider) and not isinstance(provider, type): self.providers[feature_name] = lambda: provider(*args, **kwargs) else: self.providers[feature_name] = lambda: provider
Provide a feature named ``feature_name`` using the provider object ``provider`` and any arguments (``args``, ``kwargs``) needed by the provider if it is callable.
entailment
def _urlendecode(url, func): """Encode or decode ``url`` by applying ``func`` to all of its URL-encodable parts. """ parsed = urlparse(url) for attr in URL_ENCODABLE_PARTS: parsed = parsed._replace(**{attr: func(getattr(parsed, attr))}) return urlunparse(parsed)
Encode or decode ``url`` by applying ``func`` to all of its URL-encodable parts.
entailment
def autodiscover(): """ Auto-discover INSTALLED_APPS backbone_api.py modules. """ # This code is based off django.contrib.admin.__init__ from django.conf import settings try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule from backbone.views import BackboneAPIView # This is to prevent a circular import issue for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's backbone module. try: import_module('%s.backbone_api' % app) except: # Decide whether to bubble up this error. If the app just # doesn't have an backbone module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'backbone_api'): raise
Auto-discover INSTALLED_APPS backbone_api.py modules.
entailment
def register(self, backbone_view_class): """ Registers the given backbone view class. """ if backbone_view_class not in self._registry: self._registry.append(backbone_view_class)
Registers the given backbone view class.
entailment
def queryset(self, request, **kwargs): """ Returns the queryset (along with ordering) to be used when retrieving object(s). """ qs = self.model._default_manager.all() if self.ordering: qs = qs.order_by(*self.ordering) return qs
Returns the queryset (along with ordering) to be used when retrieving object(s).
entailment
def get(self, request, id=None, **kwargs): """ Handles get requests for either the collection or an object detail. """ if not self.has_get_permission(request): return HttpResponseForbidden(_('You do not have permission to perform this action.')) if id: obj = get_object_or_404(self.queryset(request, **kwargs), id=id) return self.get_object_detail(request, obj) else: return self.get_collection(request, **kwargs)
Handles get requests for either the collection or an object detail.
entailment
def get_object_detail(self, request, obj): """ Handles get requests for the details of the given object. """ if self.display_detail_fields: display_fields = self.display_detail_fields else: display_fields = self.display_fields data = self.serialize(obj, ['id'] + list(display_fields)) return HttpResponse(self.json_dumps(data), content_type='application/json')
Handles get requests for the details of the given object.
entailment
def get_collection(self, request, **kwargs): """ Handles get requests for the list of objects. """ qs = self.queryset(request, **kwargs) if self.display_collection_fields: display_fields = self.display_collection_fields else: display_fields = self.display_fields if self.paginate_by is not None: page = request.GET.get('page', 1) paginator = Paginator(qs, self.paginate_by) try: qs = paginator.page(page).object_list except PageNotAnInteger: data = _('Invalid `page` parameter: Not a valid integer.') return HttpResponseBadRequest(data) except EmptyPage: data = _('Invalid `page` parameter: Out of range.') return HttpResponseBadRequest(data) data = [ self.serialize(obj, ['id'] + list(display_fields)) for obj in qs ] return HttpResponse(self.json_dumps(data), content_type='application/json')
Handles get requests for the list of objects.
entailment
def post(self, request, id=None, **kwargs): """ Handles post requests. """ if id: # No posting to an object detail page return HttpResponseForbidden() else: if not self.has_add_permission(request): return HttpResponseForbidden(_('You do not have permission to perform this action.')) else: return self.add_object(request)
Handles post requests.
entailment
def add_object(self, request): """ Adds an object. """ try: # backbone sends data in the body in json format # Conditional statement is for backwards compatibility with Django <= 1.3 data = json.loads(request.body if hasattr(request, 'body') else request.raw_post_data) except ValueError: return HttpResponseBadRequest(_('Unable to parse JSON request body.')) form = self.get_form_instance(request, data=data) if form.is_valid(): if not self.has_add_permission_for_data(request, form.cleaned_data): return HttpResponseForbidden(_('You do not have permission to perform this action.')) obj = form.save() # We return the newly created object's details and a Location header with it's url response = self.get_object_detail(request, obj) response.status_code = 201 opts = self.model._meta url_slug = self.url_slug or ( opts.model_name if hasattr(opts, 'model_name') else opts.module_name ) url_name = 'backbone:%s_%s_detail' % (self.model._meta.app_label, url_slug) response['Location'] = reverse(url_name, args=[obj.id]) return response else: return HttpResponseBadRequest(self.json_dumps(form.errors), content_type='application/json')
Adds an object.
entailment
def put(self, request, id=None, **kwargs): """ Handles put requests. """ if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_update_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perform this action.')) else: return self.update_object(request, obj) else: # No putting on a collection. return HttpResponseForbidden()
Handles put requests.
entailment
def update_object(self, request, obj): """ Updates an object. """ try: # backbone sends data in the body in json format # Conditional statement is for backwards compatibility with Django <= 1.3 data = json.loads(request.body if hasattr(request, 'body') else request.raw_post_data) except ValueError: return HttpResponseBadRequest(_('Unable to parse JSON request body.')) form = self.get_form_instance(request, data=data, instance=obj) if form.is_valid(): if not self.has_update_permission_for_data(request, form.cleaned_data): return HttpResponseForbidden(_('You do not have permission to perform this action.')) form.save() # We return the updated object details return self.get_object_detail(request, obj) else: return HttpResponseBadRequest(self.json_dumps(form.errors), content_type='application/json')
Updates an object.
entailment
def get_form_instance(self, request, data=None, instance=None): """ Returns an instantiated form to be used for adding or editing an object. The `instance` argument is the model instance (passed only if this form is going to be used for editing an existing object). """ defaults = {} if self.form: defaults['form'] = self.form if self.fields: defaults['fields'] = self.fields return modelform_factory(self.model, **defaults)(data=data, instance=instance)
Returns an instantiated form to be used for adding or editing an object. The `instance` argument is the model instance (passed only if this form is going to be used for editing an existing object).
entailment
def delete(self, request, id=None): """ Handles delete requests. """ if id: obj = get_object_or_404(self.queryset(request), id=id) if not self.has_delete_permission(request, obj): return HttpResponseForbidden(_('You do not have permission to perform this action.')) else: return self.delete_object(request, obj) else: # No delete requests allowed on collection view return HttpResponseForbidden()
Handles delete requests.
entailment
def has_add_permission(self, request): """ Returns True if the requesting user is allowed to add an object, False otherwise. """ perm_string = '%s.add_%s' % (self.model._meta.app_label, self.model._meta.object_name.lower() ) return request.user.has_perm(perm_string)
Returns True if the requesting user is allowed to add an object, False otherwise.
entailment
def has_update_permission(self, request, obj): """ Returns True if the requesting user is allowed to update the given object, False otherwise. """ perm_string = '%s.change_%s' % (self.model._meta.app_label, self.model._meta.object_name.lower() ) return request.user.has_perm(perm_string)
Returns True if the requesting user is allowed to update the given object, False otherwise.
entailment