def _assignGroupToUser(self, user, group, ugRoot):
""" Assign the group membership to the user
Do nothing, if it is already assigned """
# users.xml:
# <group enabled="true" name="hasici">
# <member username="hasic1"/>
# </group>
if sys.hexversion >= 0x02070000: # Python 2.7 or more
groupElem = ugRoot.find("./{http://www.geoserver.org/security/users}groups/{http://www.geoserver.org/security/users}group[@name='"+group+"']")
memberElem = grEl.find("{http://www.geoserver.org/security/users}member[@username='"+user+"']")
else: # Python 2.6 or less
groupElem = self._xPath26Find(ugRoot, "./{http://www.geoserver.org/security/users}groups/{http://www.geoserver.org/security/users}group", "name", group)
memberElem = self._xPath26Find(grEl,"{http://www.geoserver.org/security/users}member", "username", user)
if memberElem is not None: # if the group is already assigned
return # do nothing
memberElem = Xml.Element("{http://www.geoserver.org/security/users}member", {"username":user})
groupElem.append(memberElem)
python类hexversion()的实例源码
def _removeGroupFromUser(self, user, group, ugRoot):
""" Remove group membership """
if sys.hexversion >= 0x02070000: # Python 2.7 or more
groupElem = ugRoot.find("./{http://www.geoserver.org/security/users}groups/{http://www.geoserver.org/security/users}group[@name='"+group+"']")
else: # Python 2.6 or less
groupElem = self._xPath26Find(ugRoot, "./{http://www.geoserver.org/security/users}groups/{http://www.geoserver.org/security/users}group", "name", group)
if groupElem is not None:
#print "nasel grupu"
if sys.hexversion >= 0x02070000: # Python 2.7 or more
memberElem = grEl.find("{http://www.geoserver.org/security/users}member[@username='"+user+"']")
else: # Python 2.6 or less
memberElem = self._xPath26Find(grEl,"{http://www.geoserver.org/security/users}member", "username", user)
if memberElem is not None:
#print "nasel membra"
groupElem.remove(memberElem)
#else:
# print "nenasel membra"
#else:
# print "nenasel grupu"
def _createRole(self, role, rrRoot):
""" Create Role. If exists, do nothing. """
changed = False
# Check for the role
if sys.hexversion >= 0x02070000: # Python 2.7 or more
roleElem = rrRoot.find("./{http://www.geoserver.org/security/roles}roleList/{http://www.geoserver.org/security/roles}role[@id='"+role+"']")
else: # Python 2.6 or less
roleElem = self._xPath26Find(rrRoot, "./{http://www.geoserver.org/security/roles}roleList/{http://www.geoserver.org/security/roles}role", "id", role)
if roleElem is None:
# Create the role
roleElem = Xml.Element("{http://www.geoserver.org/security/roles}role", {"id":role})
roleListElem = rrRoot.find("./{http://www.geoserver.org/security/roles}roleList")
roleListElem.append(roleElem)
changed = True
return changed
def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
global _hashes
if _hashes is None:
_setup_hashes()
if isinstance(algorithm, (str, unicode)):
algorithm = dns.name.from_text(algorithm)
if sys.hexversion < 0x02050200 and \
(algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512):
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" requires Python 2.5.2 or later")
try:
return (algorithm.to_digestable(), _hashes[algorithm])
except KeyError:
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" is not supported")
def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
global _hashes
if _hashes is None:
_setup_hashes()
if isinstance(algorithm, (str, unicode)):
algorithm = dns.name.from_text(algorithm)
if sys.hexversion < 0x02050200 and \
(algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512):
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" requires Python 2.5.2 or later")
try:
return (algorithm.to_digestable(), _hashes[algorithm])
except KeyError:
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" is not supported")
def test_implementation(self):
# This test applies to all implementations equally.
levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF}
self.assertTrue(hasattr(sys.implementation, 'name'))
self.assertTrue(hasattr(sys.implementation, 'version'))
self.assertTrue(hasattr(sys.implementation, 'hexversion'))
self.assertTrue(hasattr(sys.implementation, 'cache_tag'))
version = sys.implementation.version
self.assertEqual(version[:2], (version.major, version.minor))
hexversion = (version.major << 24 | version.minor << 16 |
version.micro << 8 | levels[version.releaselevel] << 4 |
version.serial << 0)
self.assertEqual(sys.implementation.hexversion, hexversion)
# PEP 421 requires that .name be lower case.
self.assertEqual(sys.implementation.name,
sys.implementation.name.lower())
def finalize_options(self):
self.set_undefined_options('install_lib',
('install_dir', 'install_dir'))
self.set_undefined_options('install',('install_layout','install_layout'))
if sys.hexversion > 0x2060000:
self.set_undefined_options('install',('prefix_option','prefix_option'))
ei_cmd = self.get_finalized_command("egg_info")
basename = pkg_resources.Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version
).egg_name() + '.egg-info'
if self.install_layout:
if not self.install_layout.lower() in ['deb']:
raise DistutilsOptionError(
"unknown value for --install-layout")
basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')
elif self.prefix_option or 'real_prefix' in sys.__dict__:
# don't modify for virtualenv
pass
else:
basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')
self.source = ei_cmd.egg_info
self.target = os.path.join(self.install_dir, basename)
self.outputs = [self.target]
def main(argv):
if sys.hexversion < 0x02060000:
print('\nYour python version %s is unsupported, please upgrade.\n' %
(sys.version.split(' ', 1)[0],), file=sys.stderr)
return 2
# Reload settings.
global settings
settings = Settings()
colorize_CMDstatus_doc()
dispatcher = subcommand.CommandDispatcher(__name__)
try:
return dispatcher.execute(OptionParser(), argv)
except auth.AuthenticationError as e:
DieWithError(str(e))
except urllib2.HTTPError as e:
if e.code != 500:
raise
DieWithError(
('AppEngine is misbehaving and returned HTTP %d, again. Keep faith '
'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
return 0
def finalize_options(self):
self.set_undefined_options('install_lib',
('install_dir', 'install_dir'))
self.set_undefined_options('install',('install_layout','install_layout'))
if sys.hexversion > 0x2060000:
self.set_undefined_options('install',('prefix_option','prefix_option'))
ei_cmd = self.get_finalized_command("egg_info")
basename = pkg_resources.Distribution(
None, None, ei_cmd.egg_name, ei_cmd.egg_version
).egg_name() + '.egg-info'
if self.install_layout:
if not self.install_layout.lower() in ['deb']:
raise DistutilsOptionError(
"unknown value for --install-layout")
basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')
elif self.prefix_option or 'real_prefix' in sys.__dict__:
# don't modify for virtualenv
pass
else:
basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')
self.source = ei_cmd.egg_info
self.target = os.path.join(self.install_dir, basename)
self.outputs = [self.target]
def makeAscii(data):
log(repr(data), 5)
#if sys.hexversion >= 0x02050000:
# return data
try:
return data.encode('ascii', "ignore")
except:
log("Hit except on : " + repr(data))
s = u""
for i in data:
try:
i.encode("ascii", "ignore")
except:
log("Can't convert character", 4)
continue
else:
s += i
log(repr(s), 5)
return s
# This function handles stupid utf handling in python.
def main(argv):
if sys.hexversion < 0x02060000:
print('\nYour python version %s is unsupported, please upgrade.\n' %
(sys.version.split(' ', 1)[0],), file=sys.stderr)
return 2
# Reload settings.
global settings
settings = Settings()
colorize_CMDstatus_doc()
dispatcher = subcommand.CommandDispatcher(__name__)
try:
return dispatcher.execute(OptionParser(), argv)
except auth.AuthenticationError as e:
DieWithError(str(e))
except urllib2.HTTPError as e:
if e.code != 500:
raise
DieWithError(
('AppEngine is misbehaving and returned HTTP %d, again. Keep faith '
'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
return 0
def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
global _hashes
if _hashes is None:
_setup_hashes()
if isinstance(algorithm, (str, unicode)):
algorithm = name.from_text(algorithm)
if sys.hexversion < 0x02050200 and \
(algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512):
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" requires Python 2.5.2 or later")
try:
return (algorithm.to_digestable(), _hashes[algorithm])
except KeyError:
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" is not supported")
def writeln(x=''):
"""
Write x and an end-of-line mark to standard output.
"""
if sys.hexversion < 0x03000000:
x = unicode(x)
x = x.encode('utf-8')
else:
x = str(x)
sys.stdout.write(x)
sys.stdout.write('\n')
sys.stdout.flush()
#-----------------------------------------------------------------------
def write(x=''):
"""
Write x to standard output.
"""
if (sys.hexversion < 0x03000000):
x = unicode(x)
x = x.encode('utf-8')
else:
x = str(x)
sys.stdout.write(x)
sys.stdout.flush()
#-----------------------------------------------------------------------
def writef(fmt, *args):
"""
Write each element of args to standard output. Use the format
specified by string fmt.
"""
x = fmt % args
if sys.hexversion < 0x03000000:
x = unicode(x)
x = x.encode('utf-8')
sys.stdout.write(x)
sys.stdout.flush()
#=======================================================================
# Reading functions
#=======================================================================
def activateOptions(self):
if sys.hexversion >= 0x020700F0:
# strm was changed to stream
if self.log4pyProps.has_key("strm"):
# Don't override stream if it already exists
self.log4pyProps.setdefault("stream", self.log4pyProps["strm"])
del self.log4pyProps["strm"]
logging.StreamHandler.__init__(self, **self.log4pyProps)
self.setLevel(self.threshold)
def __init__(self, value, denominator=1):
"""
:param value: either an integer numerator, a
float/rational/other number, or an IFDRational
:param denominator: Optional integer denominator
"""
self._denominator = denominator
self._numerator = value
self._val = float(1)
if type(value) == Fraction:
self._numerator = value.numerator
self._denominator = value.denominator
self._val = value
if type(value) == IFDRational:
self._denominator = value.denominator
self._numerator = value.numerator
self._val = value._val
return
if denominator == 0:
self._val = float('nan')
return
elif denominator == 1:
if sys.hexversion < 0x2070000 and type(value) == float:
# python 2.6 is different.
self._val = Fraction.from_float(value)
else:
self._val = Fraction(value)
else:
self._val = Fraction(value, denominator)
def test_wrong_type(self):
"""Test a wrongly-typed filter"""
if sys.hexversion >= 0x2070000:
with self.assertRaises(ValueError):
f = JQFilter(1234)
def test_bad_syntax(self):
"""Test a filter with the wrong syntax"""
if sys.hexversion >= 0x2070000:
with self.assertRaises(ValueError):
f = JQFilter("this is bad")
def read_json(self, convert=True, encoding='utf-8'):
"""
Read and parse the contents of this node as JSON::
def build(bld):
bld.path.find_node('abc.json').read_json()
Note that this by default automatically decodes unicode strings on Python2, unlike what the Python JSON module does.
:type convert: boolean
:param convert: Prevents decoding of unicode strings on Python2
:type encoding: string
:param encoding: The encoding of the file to read. This default to UTF8 as per the JSON standard
:rtype: object
:return: Parsed file contents
"""
import json # Python 2.6 and up
object_pairs_hook = None
if convert and sys.hexversion < 0x3000000:
try:
_type = unicode
except NameError:
_type = str
def convert(value):
if isinstance(value, list):
return [convert(element) for element in value]
elif isinstance(value, _type):
return str(value)
else:
return value
def object_pairs(pairs):
return dict((str(pair[0]), convert(pair[1])) for pair in pairs)
object_pairs_hook = object_pairs
return json.loads(self.read(encoding=encoding), object_pairs_hook=object_pairs_hook)