#NEWLINE# def clean_ipv6_address( ip_str , unpack_ipv4 = False , error_message = _ ( 'This is not a valid IPv6 address.' ) ) : #NEWLINE# #INDENT# '\n    Cleans an IPv6 address string.\n\n    Validity is checked by calling is_valid_ipv6_address() - if an\n    invalid address is passed, ValidationError is raised.\n\n    Replaces the longest continuous zero-sequence with "::" and\n    removes leading zeroes and makes sure all hextets are lowercase.\n\n    Args:\n        ip_str: A valid IPv6 address.\n        unpack_ipv4: if an IPv4-mapped address is found,\n        return the plain IPv4 address (default=False).\n        error_message: An error message used in the ValidationError.\n\n    Returns:\n        A compressed IPv6 address, or the same value\n    ' #NEWLINE# best_doublecolon_start = ( - 1 ) #NEWLINE# best_doublecolon_len = 0 #NEWLINE# doublecolon_start = ( - 1 ) #NEWLINE# doublecolon_len = 0 #NEWLINE# if ( not is_valid_ipv6_address ( ip_str ) ) : #NEWLINE# #INDENT# raise ValidationError ( error_message , code = 'invalid' ) #NEWLINE# #UNINDENT# ip_str = _explode_shorthand_ip_string ( ip_str ) #NEWLINE# ip_str = _sanitize_ipv4_mapping ( ip_str ) #NEWLINE# if unpack_ipv4 : #NEWLINE# #INDENT# ipv4_unpacked = _unpack_ipv4 ( ip_str ) #NEWLINE# if ipv4_unpacked : #NEWLINE# #INDENT# return ipv4_unpacked #NEWLINE# #UNINDENT# #UNINDENT# hextets = ip_str . split ( ':' ) #NEWLINE# for index in range ( len ( hextets ) ) : #NEWLINE# #INDENT# if ( '.' not in hextets [ index ] ) : #NEWLINE# #INDENT# hextets [ index ] = hextets [ index ] . lstrip ( '0' ) #NEWLINE# #UNINDENT# if ( not hextets [ index ] ) : #NEWLINE# #INDENT# hextets [ index ] = '0' #NEWLINE# #UNINDENT# if ( hextets [ index ] == '0' ) : #NEWLINE# #INDENT# doublecolon_len += 1 #NEWLINE# if ( doublecolon_start == ( - 1 ) ) : #NEWLINE# #INDENT# doublecolon_start = index #NEWLINE# #UNINDENT# if ( doublecolon_len > best_doublecolon_len ) : #NEWLINE# #INDENT# best_doublecolon_len = doublecolon_len #NEWLINE# best_doublecolon_start = doublecolon_start #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# doublecolon_len = 0 #NEWLINE# doublecolon_start = ( - 1 ) #NEWLINE# #UNINDENT# #UNINDENT# if ( best_doublecolon_len > 1 ) : #NEWLINE# #INDENT# best_doublecolon_end = ( best_doublecolon_start + best_doublecolon_len ) #NEWLINE# if ( best_doublecolon_end == len ( hextets ) ) : #NEWLINE# #INDENT# hextets += [ '' ] #NEWLINE# #UNINDENT# hextets [ best_doublecolon_start : best_doublecolon_end ] = [ '' ] #NEWLINE# if ( best_doublecolon_start == 0 ) : #NEWLINE# #INDENT# hextets = ( [ '' ] + hextets ) #NEWLINE# #UNINDENT# #UNINDENT# result = ':' . join ( hextets ) #NEWLINE# return result . lower ( )