Python bson.dumps() Examples

The following are 20 code examples of bson.dumps(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bson , or try the search function .
Example #1
Source File: parsers.py    From djburger with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_bson_parser(self):
        factory = RequestFactory()
        with self.subTest(src_text='mixed'):
            data = {
                'name': 'John Doe',
                'mail': 'example.gmail.com',
                'themes': ['1', '2', '4'],
            }
            request = factory.post(
                '/some/url/',
                data=bson.dumps(data),
                content_type='application/json',
            )
            p = djburger.parsers.BSON()
            parsed_data = p(request)
            self.assertEqual(parsed_data, data) 
Example #2
Source File: parsers.py    From djburger with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_json_parser(self):
        factory = RequestFactory()
        with self.subTest(src_text='mixed'):
            data = {
                'name': 'John Doe',
                'mail': 'example.gmail.com',
                'themes': ['1', '2', '4'],
            }
            request = factory.post(
                '/some/url/',
                data=json.dumps(data),
                content_type='application/json',
            )
            p = djburger.parsers.JSON()
            parsed_data = p(request)
            self.assertEqual(parsed_data, data) 
Example #3
Source File: test_shard_set.py    From hermit with Apache License 2.0 5 votes vote down vote up
def test_initialize_file(self):
        shard_set = ShardSet(self.interface)
        shard_set.config.shards_file = 'shards file'

        with patch("builtins.open", mock_open()) as mock_file:
            shard_set.initialize_file()
            mock_file.assert_called_with('shards file', 'wb')
            mock_file().write.called_with(bson.dumps({})) 
Example #4
Source File: renderers.py    From djburger with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, flat=True, **kwargs):
        if not _yaml:
            raise ImportError('BSON is not installed yet')
        self.http_kwargs = {}
        super(BSON, self).__init__(
            renderer=_bson.dumps,
            content_name='obj',
            flat=flat,
            **kwargs) 
Example #5
Source File: wrapper.py    From inshack-2018 with GNU General Public License v3.0 5 votes vote down vote up
def fetch():
    # Hit local flask server
    conn = HTTPConnection(fetcher_service, 8888)
    options = []
    for conf in fetch_options.values():
        options.append(conf["key"] + "=" + str(conf["value"]).lower())
    params = bson.dumps({
        "options": options
    })
    conn.request("POST", "/?url=" + url_to_fetch, params)
    response = conn.getresponse()
    print("Stats:")
    print(response.read().decode())
    print() 
Example #6
Source File: wrapper.py    From inshack-2018 with GNU General Public License v3.0 5 votes vote down vote up
def fetch():
    # Hit local flask server
    conn = HTTPConnection(fetcher_service, 8888)
    options = []
    for conf in fetch_options.values():
        options.append(conf["key"] + "=" + str(conf["value"]).lower())
    params = bson.dumps({
        "options": options
    })
    conn.request("POST", "/?url=" + url_to_fetch, params)
    response = conn.getresponse()
    print("Stats:")
    print(response.read().decode())
    print() 
Example #7
Source File: shard.py    From hermit with Apache License 2.0 5 votes vote down vote up
def to_qr_bson(self) -> bytes:
        """Serialize this shard as BSON, suitable for a QR code"""
        return bson.dumps({self.name: self.to_bytes()}) 
Example #8
Source File: shard_set.py    From hermit with Apache License 2.0 5 votes vote down vote up
def to_bytes(self):
        data = {name: shard.to_bytes()
                for (name, shard) in self.shards.items()}
        return bson.dumps(data) 
Example #9
Source File: shard_set.py    From hermit with Apache License 2.0 5 votes vote down vote up
def initialize_file(self) -> None:
        if self.interface.confirm_initialize_file():
            with open(self.config.shards_file, 'wb') as f:
                f.write(bson.dumps({})) 
Example #10
Source File: shard_set.py    From hermit with Apache License 2.0 5 votes vote down vote up
def _ensure_shards(self, shards_expected: bool = True) -> None:
        if not self._shards_loaded:
            bdata = None

            # If the shards dont exist at the place where they
            # are expected to by, try to restore them with the externally
            # configured getPersistedShards command.
            if not os.path.exists(self.config.shards_file):
                try:
                    os.system(self.config.commands['getPersistedShards'])
                except TypeError:
                    pass

            # If for some reason the persistence layer failed to  create the
            # the shards file, we assume that we just need to initialize
            # it as an empty bson object.
            if not os.path.exists(self.config.shards_file):
                with open(self.config.shards_file, 'wb') as f:
                    f.write(bson.dumps({}))

            with open(self.config.shards_file, 'rb') as f:
                bdata = bson.loads(f.read())

            for name, shard_bytes in bdata.items():
                self.shards[name] = Shard(
                    name, shamir_share.mnemonic_from_bytes(shard_bytes))

            self._shards_loaded = True

        if len(self.shards) == 0 and shards_expected:
            raise HermitError("No shards found.  Create some by entering 'shards' mode.") 
Example #11
Source File: bson.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def load_bson():
        global BSON
        if BSON is None:
            try:
                from pymongo.bson import BSON
            except ImportError:
                from bson import dumps
                class BSON(object):
                    @staticmethod
                    def encode(obj, *args, **kwargs):
                        return dumps(obj)


    #-------------------------------------------------------------------------- 
Example #12
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def put(self, item):
        '''
        Put item to queue -> codec -> socket.

        :param item: Message object.
        :type item: dict, list or None
        '''
        if self._closed:
            raise BsonRpcError('Attempt to put items to closed queue.')
        msg_bytes = self.codec.into_frame(self.codec.dumps(item))
        with self._lock:
            self.socket.sendall(msg_bytes) 
Example #13
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def dumps(self, msg):
        try:
            return self._dumps(msg,
                               separators=(',', ':'),
                               sort_keys=True).encode('utf-8')
        except Exception as e:
            raise EncodingError(e) 
Example #14
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, extractor, framer, custom_codec_implementation=None):
        self._extractor = extractor
        self._framer = framer
        if custom_codec_implementation is not None:
            self._loads = custom_codec_implementation.loads
            self._dumps = custom_codec_implementation.dumps
        else:
            import json
            self._loads = json.loads
            self._dumps = json.dumps 
Example #15
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def dumps(self, msg):
        try:
            return self._dumps(msg)
        except Exception as e:
            raise EncodingError(e) 
Example #16
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def put(self, item):
        '''
        Put item to queue -> codec -> socket.

        :param item: Message object.
        :type item: dict, list or None
        '''
        if self._closed:
            raise BsonRpcError('Attempt to put items to closed queue.')
        msg_bytes = self.codec.into_frame(self.codec.dumps(item))
        with self._lock:
            self.socket.sendall(msg_bytes) 
Example #17
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def dumps(self, msg):
        try:
            return self._dumps(msg,
                               separators=(',', ':'),
                               sort_keys=True).encode('utf-8')
        except Exception as e:
            raise EncodingError(e) 
Example #18
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, extractor, framer, custom_codec_implementation=None):
        self._extractor = extractor
        self._framer = framer
        if custom_codec_implementation is not None:
            self._loads = custom_codec_implementation.loads
            self._dumps = custom_codec_implementation.dumps
        else:
            import json
            self._loads = json.loads
            self._dumps = json.dumps 
Example #19
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def dumps(self, msg):
        try:
            return self._dumps(msg)
        except Exception as e:
            raise EncodingError(e) 
Example #20
Source File: socket_queue.py    From py-bson-rpc with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, custom_codec_implementation=None):
        if custom_codec_implementation is not None:
            self._loads = custom_codec_implementation.loads
            self._dumps = custom_codec_implementation.dumps
        else:
            # Use implementation from pymongo or from pybson
            import bson
            if hasattr(bson, 'BSON'):
                # pymongo
                self._loads = lambda raw: bson.BSON.decode(bson.BSON(raw))
                self._dumps = lambda msg: bytes(bson.BSON.encode(msg))
            else:
                # pybson
                self._loads = bson.loads
                self._dumps = bson.dumps