本文整理汇总了Python中bson.BSON.encode方法的典型用法代码示例。如果您正苦于以下问题:Python BSON.encode方法的具体用法?Python BSON.encode怎么用?Python BSON.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bson.BSON
的用法示例。
在下文中一共展示了BSON.encode方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _send_api_description
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def _send_api_description(self, lookup_idx, thing):
""" Describes the given API call to the host """
# Here's an api description object:
# {
# "I" : (string)<index in the API lookup table>,
# "name" : (string)<API name>,
# "type" : "info",
# "category" : (string)<an API category (e.g. "memory" or "network")>
# "args" : [
# "is_success",
# "retval",
# (string)<description of the first argument>,
# (string)<description of the second argument>,
# ...
# (string)<description of the n-th argument>,
# ]
# }
self.sockets[thing.pid].sendall(BSON.encode({
"I" : lookup_idx,
"name" : thing.api,
"type" : "info",
"category" : self._api_category(thing),
"args" : self._api_args_description(thing)
}))
示例2: document_encode
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def document_encode(doc, check_keys=False, *args, **kwargs):
_encoder = BSONEncoder()
_key_sep = _encoder.key_separator
candidate = serialized = ""
for s in _encoder.iterencode(doc):
if s == _key_sep:
if not _encoder._key_is_keyword:
key = eval(candidate)
if not isinstance(key, string_types):
raise InvalidDocument(
"documents must have only string keys, key was "
"%r" % key)
if check_keys:
_key_validate(key)
_encoder._key_is_keyword = False
candidate = s
serialized += s
return serialized.encode()
示例3: test_utils_montyimport
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def test_utils_montyimport(tmp_monty_repo):
database = "dump_db_JSON"
collection = "dump_col_JSON"
if not os.path.isdir(tmp_monty_repo):
os.makedirs(tmp_monty_repo)
with open_repo(tmp_monty_repo):
with open(JSON_DUMP, "w") as dump:
dump.write(SERIALIZED)
montyimport(database, collection, JSON_DUMP)
client = MontyClient()
col = client[database][collection]
for i, doc in enumerate(col.find(sort=[("_id", 1)])):
assert doc == BSON.encode(DOCUMENTS[i]).decode()
os.remove(JSON_DUMP)
示例4: write
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def write(self, do_merge=False):
f = None
try:
self.lock.acquire()
if do_merge and os.path.isfile(self.state_file):
curr = self.load(True)
self.merge(self.state, curr)
f = open(self.state_file, 'w+')
logging.debug("Writing %s state file: %s" % (self.__class__.__name__, self.state_file))
self.state['updated_at'] = int(time())
f.write(BSON.encode(self.state))
finally:
if f:
f.close()
self.lock.release()
示例5: add
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def add(self, doc, autoflush=True):
try:
self._oplog.write(BSON.encode(doc))
self._writes_unflushed += 1
self._count += 1
if not self._first_ts:
self._first_ts = doc['ts']
self._last_ts = doc['ts']
if autoflush:
self.autoflush()
except Exception, e:
logging.fatal("Cannot write to oplog file %s! Error: %s" % (self.oplog_file, e))
raise OperationError(e)
示例6: _send_new_process
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def _send_new_process(self, thing):
""" Sends a notification about a new target process out there """
pid = thing.pid
lookup_idx = self.descriptions[pid].index("__process__")
# Remember when this process was born
self.launch_times[pid] = thing.timestamp
# Describe the __process__ notification
self.sockets[pid].sendall(BSON.encode({
"I" : lookup_idx,
"name" : "__process__",
"type" : "info",
"category" : "unknown",
"args" : [
"is_success",
"retval",
"TimeLow", "TimeHigh",
"ProcessIdentifier", "ParentProcessIdentifier",
"ModulePath"
]
}))
# Convert our unix timestamp into Windows's FILETIME because Cuckoo
# result server expect timestamps to be in this format
filetime = _filetime_from_timestamp(thing.timestamp)
# Get process name (aka module path)
module = _proc_name_from_pid(pid)
self.sockets[pid].sendall(BSON.encode({
"I" : lookup_idx,
"T" : thing.tid,
"t" : 0,
"args" : [
1,
0,
# TimeLow (first 32bits) and TimeHigh (last 32bits)
filetime & 0xffffffff, filetime >> 32,
thing.pid, thing.ppid,
# ModulePath
module
]
}))
示例7: testAbortWithBSON
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def testAbortWithBSON(self):
tmp = self.plugin.abort_with_bson(401, {"kk": 2})
self.assertIsInstance(tmp, HTTPResponse)
self.assertEquals("application/bson", tmp.content_type)
self.assertEquals(401, tmp.status_code)
self.assertEquals(str(BSON.encode({"kk": 2})), tmp.body)
示例8: __set_bson_content
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def __set_bson_content(self, data):
bottle.request.environ['wsgi.input'] = str(BSON.encode(data))
bottle.request.environ["CONTENT_LENGTH"] = len(bottle.request.environ['wsgi.input'])
bottle.request.body = Mock
bottle.request.body.read = Mock(return_value=bottle.request.environ['wsgi.input'])
示例9: montydump
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def montydump(database, collection, dumpfile):
"""Creates a binary export from a MontyCollection instance
The export should be able to be accepted by `mongorestore`.
Example:
>>> from montydb import open_repo, utils
>>> with open_repo("foo/bar"):
>>> utils.montydump("db", "col", "/data/dump.bson")
>>>
Args:
database (str): Database name
collection (str): Collection name to export from
dumpfile (str): File path to export to
"""
collection = _collection(database, collection)
dumpfile = os.path.abspath(dumpfile)
if not os.path.isdir(os.path.dirname(dumpfile)):
os.makedirs(os.path.dirname(dumpfile))
raw = b""
for doc in collection.find():
raw += BSON.encode(doc)
with open(dumpfile, "wb") as fp:
fp.write(raw)
示例10: encode_
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def encode_(s):
return s.encode("utf-8")
示例11: create_beacon_payload
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def create_beacon_payload(beacon_type, payload=None, version=PROTOCOL_VERSION):
"""Creates a beacon payload of the specified type, with the given data.
:param beacon_type: The beacon packet type. Indicates the purpose of the
beacon to the receiver.
:param payload: Optional JSON-encodable dictionary. Will be converted to an
inner encrypted payload and presented in the "data" field in the
resulting dictionary.
:param version: Optional protocol version to use (defaults to most recent).
:return: BeaconPayload namedtuple representing the packet bytes, the outer
payload, and the inner encrypted data (if any).
"""
beacon_type_code = BEACON_TYPES[beacon_type]
if payload is not None:
payload = payload.copy()
payload["uuid"] = str(uuid.uuid1())
payload["type"] = beacon_type_code
data_bytes = BSON.encode(payload)
compressed_bytes = compress(data_bytes, compresslevel=9)
payload_bytes = fernet_encrypt_psk(compressed_bytes, raw=True)
else:
payload_bytes = b""
beacon_bytes = struct.pack(
BEACON_HEADER_FORMAT_V1 + "%ds" % len(payload_bytes),
version,
beacon_type_code,
len(payload_bytes),
payload_bytes,
)
return BeaconPayload(
beacon_bytes, version, BEACON_TYPE_VALUES[beacon_type_code], payload
)
示例12: create_loco_packet
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def create_loco_packet(self, command, args):
packet = "\xFF\xFF\xFF\xFF"
packet += "\x00\x00"
packet += command + "\x00" * (11 - len(command))
packet += "\x00"
body = BSON.encode(args)
packet += body[:4]
packet += body
return packet
示例13: send_api
# 需要导入模块: from bson import BSON [as 别名]
# 或者: from bson.BSON import encode [as 别名]
def send_api(self, thing):
""" Sends a new API notification to the Cuckoo host """
pid = thing.pid
api = thing.api
# We're required to report results of tracing a target process to
# *its own* result server. So create a communication socket...
if pid not in self.sockets:
self.sockets[pid] = self._create_socket()
if not self.sockets[pid]:
raise Exception("CuckooHost error: could not create socket.")
# ... and don't forget to explain every single API call again
self.descriptions.setdefault(pid, ["__process__", "__thread__"])
self._send_new_process(thing)
try:
lookup_idx = self.descriptions[pid].index(api)
except ValueError:
self.descriptions[pid].append(api)
lookup_idx = len(self.descriptions[pid]) - 1
self._send_api_description(lookup_idx, thing)
# Here's an api object:
# {
# "I" : (int)<index in the API lookup table>,
# "T" : (int)<caller thread id>,
# "t" : (int)<time (in milliseconds) since a process launch>,
# "args" : [
# (int)<1 if this API call was successfull, 0 otherwise>,
# (int)<return value>,
# (any)<value the first argument>,
# (any)<value the second argument>,
# ...
# (any)<value the n-th argument>,
# ]
# }
time_offset_ms = int(1000*thing.timestamp - 1000*self.launch_times[pid])
self.sockets[pid].sendall(BSON.encode({
"I" : lookup_idx,
"T" : thing.tid,
"t" : time_offset_ms,
"args" : self._prepare_args(thing)
}))