本文整理汇总了Python中dNG.data.binary.Binary类的典型用法代码示例。如果您正苦于以下问题:Python Binary类的具体用法?Python Binary怎么用?Python Binary使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Binary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_data_attributes
def set_data_attributes(self, **kwargs):
"""
Sets values given as keyword arguments to this method.
:since: v0.2.00
"""
with self:
if ("type" in kwargs):
_type = (kwargs['type'] if (type(kwargs['type']) is int) else self.__class__.get_type_int(kwargs['type']))
self.local.db_instance.type = _type
#
if ("type_ex" in kwargs): self.local.db_instance.type_ex = kwargs['type_ex']
if ("banned" in kwargs): self.local.db_instance.banned = kwargs['banned']
if ("deleted" in kwargs): self.local.db_instance.deleted = kwargs['deleted']
if ("locked" in kwargs): self.local.db_instance.locked = kwargs['locked']
if ("name" in kwargs): self.local.db_instance.name = Binary.utf8(kwargs['name'])
if ("password" in kwargs): self.local.db_instance.password = kwargs['password']
if ("lang" in kwargs): self.local.db_instance.lang = kwargs['lang']
if ("theme" in kwargs): self.local.db_instance.theme = kwargs['theme']
if ("email" in kwargs): self.local.db_instance.email = Binary.utf8(kwargs['email'])
if ("email_public" in kwargs): self.local.db_instance.email_public = kwargs['email_public']
if ("credits" in kwargs): self.local.db_instance.credits = kwargs['credits']
if ("title" in kwargs): self.local.db_instance.title = Binary.utf8(kwargs['title'])
if ("avatar" in kwargs): self.local.db_instance.avatar = kwargs['avatar']
if ("signature" in kwargs): self.local.db_instance.signature = Binary.utf8(kwargs['signature'])
if ("registration_ip" in kwargs): self.local.db_instance.registration_ip = kwargs['registration_ip']
if ("registration_time" in kwargs): self.local.db_instance.registration_time = int(kwargs['registration_time'])
if ("secid" in kwargs): self.local.db_instance.secid = kwargs['secid']
if ("lastvisit_ip" in kwargs): self.local.db_instance.lastvisit_ip = kwargs['lastvisit_ip']
if ("lastvisit_time" in kwargs): self.local.db_instance.lastvisit_time = int(kwargs['lastvisit_time'])
if ("rating" in kwargs): self.local.db_instance.rating = kwargs['rating']
if ("timezone" in kwargs): self.local.db_instance.timezone = kwargs['timezone']
示例2: send
def send(self, data = None):
"""
Invoke an SSDP M-SEARCH method on the unicast or multicast recipient.
:return: (bool) Request result
:since: v0.2.00
"""
if (data is not None): data = Binary.utf8_bytes(data)
headers = self.headers.copy()
headers['CONTENT-LENGTH'] = (0 if (data is None) else len(data))
headers['SERVER'] = AbstractSsdp.get_pas_upnp_sddp_identifier_string()
ssdp_header = "{0} {1}\r\n".format(AbstractSsdp.get_pas_upnp_http_header_string(True),
self.http_status
)
for header_name in headers:
if (type(headers[header_name]) is list):
for header_value in headers[header_name]: ssdp_header += "{0}: {1}\r\n".format(header_name, header_value)
else: ssdp_header += "{0}: {1}\r\n".format(header_name, headers[header_name])
#
ssdp_header = Binary.utf8_bytes("{0}\r\n".format(ssdp_header))
data = (ssdp_header if (data is None) else ssdp_header + data)
return self._write_data(data)
示例3: request
def request(self, method, data = None):
"""
Invoke a given SSDP method on the unicast or multicast recipient.
:param method: HTTP method
:param data: HTTP body
:return: (bool) Request result
:since: v0.2.00
"""
if (data is not None): data = Binary.utf8_bytes(data)
headers = self.headers.copy()
headers['HOST'] = "{0}:{1:d}".format(self.host, self.port)
headers['CONTENT-LENGTH'] = (0 if (data is None) else len(data))
headers['SERVER'] = AbstractSsdp.get_pas_upnp_sddp_identifier_string()
ssdp_header = "{0} {1} {2}\r\n".format(method.upper(),
self.path,
AbstractSsdp.get_pas_upnp_http_header_string(True)
)
for header_name in headers:
if (type(headers[header_name]) is list):
for header_value in headers[header_name]: ssdp_header += "{0}: {1}\r\n".format(header_name, header_value)
else: ssdp_header += "{0}: {1}\r\n".format(header_name, headers[header_name])
#
ssdp_header = Binary.utf8_bytes("{0}\r\n".format(ssdp_header))
data = (ssdp_header if (data is None) else ssdp_header + data)
return self._write_data(data)
示例4: set_data_attributes
def set_data_attributes(self, **kwargs):
"""
Sets values given as keyword arguments to this method.
:since: v0.2.00
"""
with self, self.local.connection.no_autoflush:
DataLinker.set_data_attributes(self, **kwargs)
if ("entry_type" in kwargs): self.local.db_instance.entry_type = kwargs['entry_type']
if ("owner_type" in kwargs): self.local.db_instance.owner_type = kwargs['owner_type']
if ("author_id" in kwargs): self.local.db_instance.author_id = kwargs['author_id']
if ("author_ip" in kwargs): self.local.db_instance.author_ip = kwargs['author_ip']
if ("time_published" in kwargs): self.local.db_instance.time_published = int(kwargs['time_published'])
if ("description" in kwargs): self.local.db_instance.description = Binary.utf8(kwargs['description'])
if ("locked" in kwargs): self.local.db_instance.locked = kwargs['locked']
if ("guest_permission" in kwargs): self.local.db_instance.guest_permission = kwargs['guest_permission']
if ("user_permission" in kwargs): self.local.db_instance.user_permission = kwargs['user_permission']
if ("content" in kwargs):
if (self.local.db_instance.rel_text_entry is None):
self.local.db_instance.rel_text_entry = _DbTextEntry()
self.local.db_instance.rel_text_entry.id = self.local.db_instance.id
db_text_entry = self.local.db_instance.rel_text_entry
else: db_text_entry = self.local.db_instance.rel_text_entry
db_text_entry.content = Binary.utf8(kwargs['content'])
示例5: _get_blake2_password
def _get_blake2_password(self, variant, password, username = None):
"""
Returns the BLAKE2 generated password hash.
:param password: User profile password
:param username: User name used while generating BLAKE2 hash
:return: (str) Hash on success; None if not supported
:since: v0.2.00
"""
blake2 = None
blake2_person = None
blake2_salt = None
salt = Settings.get("pas_user_profile_password_salt")
if (salt is None): raise ValueException("User profile password salt is not defined")
if (variant == PasswordGeneratorsMixin.PASSWORD_TYPE_BLAKE2B):
blake2 = blake2b
blake2_salt = Binary.bytes(salt[:blake2b.SALT_SIZE])
blake2_person = Binary.utf8_bytes(username[:blake2b.PERSON_SIZE])
#
if (variant == PasswordGeneratorsMixin.PASSWORD_TYPE_BLAKE2S):
blake2 = blake2s
blake2_salt = Binary.bytes(salt[:blake2s.SALT_SIZE])
blake2_person = Binary.utf8_bytes(username[:blake2s.PERSON_SIZE])
#
if (blake2 is None): raise ValueException("BLAKE2 variant given is invalid")
return blake2(Binary.utf8_bytes(password), salt = blake2_salt, person = blake2_person).hexdigest()
示例6: read
def read(self, n = 0):
"""
Reads data using the given body reader and parse the JSON response. Chunked
transfer-encoded data is handled automatically.
:param n: Bytes to read
:return: (bytes) Data received
:since: v1.0.0
"""
# pylint: disable=access-member-before-definition, attribute-defined-outside-init, not-callable, used-before-assignment
if (n > 0): raise OperationNotSupportedException()
if (self.json_resource is None):
json_data = self.body_reader()
self.body_reader = None
self.json_resource = JsonResource()
self.json_resource.parse(Binary.str(json_data))
if (self.json_resource.data is None): raise ValueException("Data received is not a valid JSON encoded response")
_return = Binary.bytes(json_data)
else: _return = Binary.bytes("")
return _return
示例7: get_native
def get_native(native_type, value):
"""
Returns the native value for the given variable definition and UPnP encoded
value.
:param native_type: Native type definition
:param value: Native python value
:return: (str) UPnP encoded value
:since: v0.2.00
"""
if (type(native_type) is tuple):
if (native_type[1] == "xmlns"): _return = value
elif (native_type[1] == "base64"): _return = Binary.raw_str(b64decode(Binary.utf8_bytes(value)))
elif (native_type[1] == "date"): _return = RfcBasics.get_iso8601_timestamp(value, has_time = False)
elif (native_type[1] == "dateTime"): _return = RfcBasics.get_iso8601_timestamp(value, has_timezone = False)
elif (native_type[1] == "dateTime.tz"): _return = RfcBasics.get_iso8601_timestamp(value)
elif (native_type[1] == "hex"): _return = Binary.raw_str(unhexlify(Binary.utf8_bytes(value)))
elif (native_type[1] == "time"): _return = RfcBasics.get_iso8601_timestamp(value, False, has_timezone = False)
elif (native_type[1] == "time.tz"): _return = RfcBasics.get_iso8601_timestamp(value, False)
elif (native_type[1] == "uri" and re.match("^\\w+\\:\\w", value) is None): raise ValueException("Given value mismatches defined format for URIs")
elif (native_type[1] == "uuid" and (not value.startswith("uuid:"))): raise ValueException("Given value mismatches defined format for UUIDs")
elif (native_type[0] is not str): _return = native_type[0](value)
elif (native_type is not str): _return = native_type(value)
else: _return = value
return _return
示例8: init_metadata_xml_tree
def init_metadata_xml_tree(self, device_identifier, url_base, xml_resource):
"""
Initialize the service metadata from a UPnP description.
:param device_identifier: Parsed UPnP device identifier
:param url_base: HTTP base URL
:param xml_resource: UPnP description XML parser instance
:return: (bool) True if parsed successfully
:since: v0.2.00
"""
_return = True
if (xml_resource.count_node("upnp:service") > 0): xml_resource.set_cached_node("upnp:service")
else: _return = False
if (_return):
value = xml_resource.get_node_value("upnp:service upnp:serviceType")
re_result = (None if (value is None) else Service.RE_USN_URN.match(value))
if (re_result is None or re_result.group(2) != "service"): _return = False
else:
self.name = "{0}:service:{1}".format(re_result.group(1), re_result.group(3))
urn = "{0}:{1}".format(self.name, re_result.group(4))
self._set_identifier({ "device": device_identifier['device'],
"bootid": device_identifier['bootid'],
"configid": device_identifier['configid'],
"uuid": device_identifier['uuid'],
"class": "service",
"usn": "uuid:{0}::{1}".format(device_identifier['uuid'], value),
"urn": urn,
"domain": re_result.group(1),
"type": re_result.group(3),
"version": re_result.group(4)
})
#
#
if (_return):
value = xml_resource.get_node_value("upnp:service upnp:serviceId")
re_result = (None if (value is None) else Service.RE_SERVICE_ID_URN.match(value))
if (re_result is None or re_result.group(2) != "serviceId"): _return = False
else: self.service_id = { "urn": value[4:], "domain": re_result.group(1), "id": re_result.group(3) }
#
if (_return):
self.url_scpd = Binary.str(urljoin(url_base, xml_resource.get_node_value("upnp:service upnp:SCPDURL")))
self.url_control = Binary.str(urljoin(url_base, xml_resource.get_node_value("upnp:service upnp:controlURL")))
value = xml_resource.get_node_value("upnp:service upnp:eventSubURL")
self.url_event_control = (None if (value.strip == "") else Binary.str(urljoin(url_base, value)))
#
return _return
示例9: get_url_base
def get_url_base(self, _type, parameters):
"""
Returns the base URL for the given type and parameters.
:param _type: Link type (see constants)
:param parameters: Link parameters
:return: (str) Base URL
:since: v0.2.00
"""
_return = ""
if (_type & Link.TYPE_PREDEFINED_URL == Link.TYPE_PREDEFINED_URL):
if ("__link__" not in parameters): raise ValueException("Required parameter not defined for the predefined URL")
_return = parameters['__link__']
elif (self.path is not None):
if (_type & Link.TYPE_RELATIVE_URL != Link.TYPE_RELATIVE_URL):
if (self.scheme is None): raise ValueException("Can't construct an absolute URL without an URI scheme")
_return = "{0}://".format(Binary.str(self.scheme))
if (self.host is None): raise ValueException("Can't construct an absolute URL without a host")
_return += Binary.str(self.host)
if (self.port is not None):
port = Link.filter_well_known_port(self.scheme, self.port)
if (port > 0): _return += ":{0:d}".format(port)
#
#
path = ("/" if (self.path is None) else Binary.str(self.path))
_return += ("/" if (path == "") else path)
else:
request = AbstractHttpRequest.get_instance()
if (request is None): raise ValueException("Can't construct an URL from a request instance if it is not provided")
if (_type & Link.TYPE_ABSOLUTE_URL == Link.TYPE_ABSOLUTE_URL):
scheme = request.get_server_scheme()
_return = "{0}://".format(Binary.str(scheme))
host = request.get_server_host()
if (host is not None): _return += Binary.str(host)
port = Link.filter_well_known_port(scheme, request.get_server_port())
if (port > 0): _return += ":{0:d}".format(port)
if (_type & Link.TYPE_BASE_PATH == Link.TYPE_BASE_PATH
or _type & Link.TYPE_VIRTUAL_PATH == Link.TYPE_VIRTUAL_PATH
): _return += self._get_url_path(request, False)
else: _return += self._get_url_path(request)
else: _return = self._get_url_path(request)
#
return _return
示例10: set_data_attributes
def set_data_attributes(self, **kwargs):
"""
Sets values given as keyword arguments to this method.
:since: v0.2.00
"""
with self:
MpEntry.set_data_attributes(self, **kwargs)
if ("duration" in kwargs): self.local.db_instance.duration = kwargs['duration']
if ("description" in kwargs): self.local.db_instance.description = Binary.utf8(kwargs['description'])
if ("genre" in kwargs): self.local.db_instance.genre = Binary.utf8(kwargs['genre'])
if ("series" in kwargs): self.local.db_instance.series = Binary.utf8(kwargs['series'])
if ("episode" in kwargs): self.local.db_instance.episode = kwargs['episode']
if ("actor" in kwargs): self.local.db_instance.actor = Binary.utf8(kwargs['actor'])
if ("author" in kwargs): self.local.db_instance.author = Binary.utf8(kwargs['author'])
if ("director" in kwargs): self.local.db_instance.director = Binary.utf8(kwargs['director'])
if ("producer" in kwargs): self.local.db_instance.producer = Binary.utf8(kwargs['producer'])
if ("publisher" in kwargs): self.local.db_instance.publisher = Binary.utf8(kwargs['publisher'])
if ("width" in kwargs): self.local.db_instance.width = kwargs['width']
if ("height" in kwargs): self.local.db_instance.height = kwargs['height']
if ("codec" in kwargs): self.local.db_instance.codec = kwargs['codec']
if ("bitrate" in kwargs): self.local.db_instance.bitrate = kwargs['bitrate']
if ("bpp" in kwargs): self.local.db_instance.bpp = kwargs['bpp']
if ("encoder" in kwargs): self.local.db_instance.encoder = Binary.utf8(kwargs['encoder'])
示例11: request
def request(self, _hook, **kwargs):
"""
Requests the IPC aware application to call the given hook.
:param _hook: Hook
:param args: Parameters
:return: (mixed) Result data; None on error
:since: v0.3.00
"""
_hook = Binary.str(_hook)
if (self.log_handler is not None): self.log_handler.debug("#echo(__FILEPATH__)# -{0!r}.request({1})- (#echo(__LINE__)#)", self, _hook, context = "pas_bus")
_return = None
if (not self.connected): raise IOException("Connection already closed")
request_message = self._get_message_call_template()
if (_hook == "dNG.pas.Status.stop"): request_message.set_flags(Message.FLAG_NO_REPLY_EXPECTED)
request_message_body = { "method": _hook }
if (len(kwargs) > 0): request_message_body['params'] = TypeObject("a{sv}", kwargs)
request_message.set_body(request_message_body)
if (not self._write_message(request_message)): raise IOException("Failed to transmit request")
if (_hook == "dNG.pas.Status.stop"): self.connected = False
else:
response_message = self._get_response_message()
if (((not response_message.is_error()) and (not response_message.is_method_reply()))
or response_message.get_reply_serial() != 1
or response_message.get_serial() != 2
): raise IOException("IPC response received is invalid")
if (response_message.is_error()):
response_body = response_message.get_body()
raise IOException(Binary.str(response_body)
if (type(response_body) == Binary.BYTES_TYPE) else
response_message.get_error_name()
)
else: _return = response_message.get_body()
#
return _return
示例12: theme
def theme(self, theme):
"""
Sets the theme to use.
:param theme: Output theme
:since: v1.0.0
"""
theme = Binary.str(theme)
"""
Set theme or reset to None to use the default one configured
"""
if (theme is None): self._theme = None
else:
theme_path = InputFilter.filter_file_path(theme).replace(".", path.sep)
file_path_name = path.join(self.path, theme_path, "site.tsc")
if (os.access(file_path_name, os.R_OK)): self._theme = theme
else: self._theme = None
#
"""
Read corresponding theme configuration
"""
if (self._theme is None): file_path_name = path.join(self.path, self.theme.replace(".", path.sep), "site.tsc")
file_path_name = file_path_name[:-3] + "json"
Settings.read_file(file_path_name)
示例13: _add_metadata_to_didl_xml_node
def _add_metadata_to_didl_xml_node(self, xml_resource, xml_node_path, parent_id = None):
"""
Uses the given XML resource to add the DIDL metadata of this UPnP resource.
:param xml_resource: XML resource
:param xml_base_path: UPnP resource XML base path (e.g. "DIDL-Lite
item")
:since: v0.2.00
"""
if (self.get_type() & AbstractResource.TYPE_CDS_RESOURCE == AbstractResource.TYPE_CDS_RESOURCE):
attributes = { }
didl_fields = self.get_didl_fields()
res_protocol = self.get_didl_res_protocol()
size = self.get_size()
if (res_protocol is not None): attributes['protocolInfo'] = res_protocol
if (size is not None): attributes['size'] = size
didl_fields_filtered = (len(didl_fields) > 0)
metadata = self.get_metadata()
for key in metadata:
if ((not didl_fields_filtered) or "[email protected]{0}".format(key) in didl_fields): attributes[key] = metadata[key]
#
url = Binary.str(self.get_content(0))
value = (url if (type(url) is str) else "")
xml_resource.add_node(xml_node_path, value, attributes)
示例14: compress
def compress(self, string):
"""
python.org: Compress string, returning a string containing compressed data
for at least part of the data in string.
:param string: Original string
:return: (bytes) Compressed string
:since: v1.0.0
"""
if (self.compressor is None): raise IOException("Gzip compressor already flushed and closed")
data = Binary.bytes(string)
if (self.size is None): compressed_data = self.compressor.compress(data)
else:
self.crc32 = (crc32(data) if (self.crc32 is None) else crc32(data, self.crc32))
self.size += len(data)
compressed_data = (self.compressor.compress(data) if (self.header is None) else self.compressor.compress(data)[2:])
#
if (self.header is None): _return = compressed_data
else:
_return = self.header + compressed_data
self.header = None
#
return _return
示例15: send_error
def send_error(self, code, description):
"""
Returns a UPNP response for the requested SOAP action.
:param code: UPnP error code
:param description: UPnP error description
:since: v0.2.00
"""
xml_resource = XmlResource()
xml_resource.add_node("s:Envelope", attributes = { "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/", "s:encodingStyle": "http://schemas.xmlsoap.org/soap/encoding/" })
xml_resource.add_node("s:Envelope s:Body s:Fault faultcode", "Client")
xml_resource.set_cached_node("s:Envelope s:Body")
xml_resource.add_node("s:Envelope s:Body s:Fault faultstring", "UPnPError")
xml_resource.add_node("s:Envelope s:Body s:Fault detail UPnPError", attributes = { "xmlns": "urn:schemas-upnp-org:control-1.0" })
xml_resource.set_cached_node("s:Envelope s:Body s:Fault detail UPnPError")
xml_resource.add_node("s:Envelope s:Body s:Fault detail UPnPError errorCode", code)
xml_resource.add_node("s:Envelope s:Body s:Fault detail UPnPError errorDescription", description)
self.data = Binary.utf8_bytes("<?xml version='1.0' encoding='UTF-8' ?>{0}".format(xml_resource.export_cache(True)))
self.send()