Python jsonpickle.dumps() Examples

The following are 23 code examples of jsonpickle.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 jsonpickle , or try the search function .
Example #1
Source File: plugin.py    From declaracad with GNU General Public License v3.0 6 votes vote down vote up
def export(self, event):
        """ Export the current model to stl """
        from twisted.internet import reactor
        options = event.parameters.get('options')
        if not options:
            raise ValueError("An export `options` parameter is required")

        # Pickle the configured exporter and send it over
        cmd = [sys.executable]
        if not sys.executable.endswith('declaracad'):
            cmd.extend(['-m', 'declaracad'])

        data = jsonpickle.dumps(options)
        assert data != 'null', f"Exporter failed to serialize: {options}"
        cmd.extend(['export', data])

        log.debug(" ".join(cmd))
        protocol = ProcessLineReceiver()
        reactor.spawnProcess(
            protocol, sys.executable, args=cmd, env=os.environ)
        return protocol 
Example #2
Source File: process.py    From incubator-ariatosca with Apache License 2.0 6 votes vote down vote up
def _execute(self, ctx):
        self._check_closed()

        # Temporary file used to pass arguments to the started subprocess
        file_descriptor, arguments_json_path = tempfile.mkstemp(prefix='executor-', suffix='.json')
        os.close(file_descriptor)
        with open(arguments_json_path, 'wb') as f:
            f.write(pickle.dumps(self._create_arguments_dict(ctx)))

        env = self._construct_subprocess_env(task=ctx.task)
        # Asynchronously start the operation in a subprocess
        proc = subprocess.Popen(
            [
                sys.executable,
                os.path.expanduser(os.path.expandvars(__file__)),
                os.path.expanduser(os.path.expandvars(arguments_json_path))
            ],
            env=env)

        self._tasks[ctx.task.id] = _Task(ctx=ctx, proc=proc) 
Example #3
Source File: flask_helper.py    From sanskrit_parser with MIT License 6 votes vote down vote up
def site_map():
    output = []
    for rule in app.url_map.iter_rules():
        options = {}
    for arg in rule.arguments:
        options[arg] = "[{0}]".format(arg)

    methods = ','.join(rule.methods)
    url = str(rule)
    import urllib.request

    line = urllib.request.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url))
    output.append(line)

    logging.info(str(output))
    response = app.response_class(
      response=jsonpickle.dumps(output),
      status=200,
      mimetype='application/json'
    )
    return response 
Example #4
Source File: process.py    From incubator-ariatosca with Apache License 2.0 5 votes vote down vote up
def _send_message(connection, message):

    # Packing the length of the entire msg using struct.pack.
    # This enables later reading of the content.
    def _pack(data):
        return struct.pack(_INT_FMT, len(data))

    data = jsonpickle.dumps(message)
    msg_metadata = _pack(data)
    connection.send(msg_metadata)
    connection.sendall(data) 
Example #5
Source File: utils.py    From keras-text with MIT License 5 votes vote down vote up
def dump(obj, file_name):
    if file_name.endswith('.json'):
        with open(file_name, 'w') as f:
            f.write(jsonpickle.dumps(obj))
        return

    if isinstance(obj, np.ndarray):
        np.save(file_name, obj)
        return

    # Using joblib instead of pickle because of http://bugs.python.org/issue11564
    joblib.dump(obj, file_name, protocol=pickle.HIGHEST_PROTOCOL) 
Example #6
Source File: io.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def json_pickle(file_name: Union[Text, Path], obj: Any) -> None:
    """Pickle an object to a file using json.

    Args:
        file_name: the file to store the object to
        obj: the object to store
    """
    import jsonpickle.ext.numpy as jsonpickle_numpy
    import jsonpickle

    jsonpickle_numpy.register_handlers()

    write_text_file(jsonpickle.dumps(obj), file_name) 
Example #7
Source File: io.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def dump_obj_as_json_to_file(filename: Union[Text, Path], obj: Any) -> None:
    """Dump an object as a json string to a file."""

    write_text_file(json.dumps(obj, indent=2), filename) 
Example #8
Source File: simulation_broker.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def get_state(self):
        return jsonpickle.dumps({
            'open_orders': [o.get_state() for account, o in self._open_orders],
            'delayed_orders': [o.get_state() for account, o in self._delayed_orders]
        }).encode('utf-8') 
Example #9
Source File: persisit_helper.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def get_state(self):
        result = {}
        for key, obj in six.iteritems(self._objects):
            state = obj.get_state()
            if state is not None:
                result[key] = state

        return jsonpickle.dumps(result).encode('utf-8') 
Example #10
Source File: utils.py    From declaracad with GNU General Public License v3.0 5 votes vote down vote up
def send_message(self, message):
        response = {'jsonrpc': '2.0'}
        response.update(message)
        self.transport.write(jsonpickle.dumps(response).encode()+b'\r\n') 
Example #11
Source File: workspace.py    From declaracad with GNU General Public License v3.0 5 votes vote down vote up
def save_area(self):
        """ Save the dock area for the workspace.

        """
        area = self.content.find('dock_area')
        try:
            with open('declaracad.workspace.db', 'w') as f:
                f.write(pickle.dumps(area))
        except Exception as e:
            print("Error saving dock area: {}".format(e))
            return e 
Example #12
Source File: plugin.py    From declaracad with GNU General Public License v3.0 5 votes vote down vote up
def send_message(self, method, *args, **kwargs):
        # Defer until it's ready
        if not self.transport or not self.window_id:
            #log.debug('renderer | message not ready deferring')
            timed_call(1000, self.send_message, method, *args, **kwargs)
            return
        _id = kwargs.pop('_id')
        _silent = kwargs.pop('_silent', False)

        request = {'jsonrpc': '2.0', 'method': method, 'params': args or kwargs}
        if _id is not None:
            request['id'] = _id
        if not _silent:
            log.debug(f'renderer | sent | {request}')
        self.transport.write(jsonpickle.dumps(request).encode()+b'\r\n') 
Example #13
Source File: plugin.py    From declaracad with GNU General Public License v3.0 5 votes vote down vote up
def format(self):
        """ Return formatted option values for the exporter app to parse """
        return json.dumps(self.__getstate__()) 
Example #14
Source File: base.py    From django-herald with MIT License 5 votes vote down vote up
def send(self, raise_exception=False, user=None):
        """
        Handles the preparing the notification for sending. Called to trigger the send from code.
        If raise_exception is True, it will raise any exceptions rather than simply logging them.
        returns boolean whether or not the notification was sent successfully
        """
        context = self.get_context_data()

        recipients = self.get_recipients()

        if 'text' in self.render_types:
            text_content = self.render('text', context)
        else:
            text_content = None

        if 'html' in self.render_types:
            html_content = self.render('html', context)
        else:
            html_content = None

        sent_from = self.get_sent_from()
        subject = self.get_subject()
        extra_data = self.get_extra_data()

        sent_notification = SentNotification(
            recipients=','.join(recipients),
            text_content=text_content,
            html_content=html_content,
            sent_from=sent_from,
            subject=subject,
            extra_data=json.dumps(extra_data) if extra_data else None,
            notification_class=self.get_class_path(),
            attachments=self._get_encoded_attachments(),
            user=user,
        )

        return self.resend(sent_notification, raise_exception=raise_exception) 
Example #15
Source File: simulation_broker.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def get_state(self):
        return jsonpickle.dumps({
            'open_orders': [o.get_state() for account, o in self._open_orders],
            'delayed_orders': [o.get_state() for account, o in self._delayed_orders]
        }).encode('utf-8') 
Example #16
Source File: persisit_helper.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def get_state(self):
        result = {}
        for key, obj in six.iteritems(self._objects):
            state = obj.get_state()
            if state is not None:
                result[key] = state

        return jsonpickle.dumps(result).encode('utf-8') 
Example #17
Source File: simulation_broker.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def get_state(self):
        return jsonpickle.dumps([o.order_id for _, o in self._delayed_orders]).encode('utf-8') 
Example #18
Source File: simulation_broker.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def get_state(self):
        return jsonpickle.dumps([o.order_id for _, o in self._delayed_orders]).encode('utf-8') 
Example #19
Source File: persisit_helper.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def get_state(self):
        result = {}
        for key, obj in six.iteritems(self._objects):
            state = obj.get_state()
            if state is not None:
                result[key] = state

        return jsonpickle.dumps(result).encode('utf-8') 
Example #20
Source File: broker.py    From puppet with MIT License 5 votes vote down vote up
def get_state(self):
        return jsonpickle.dumps([o.order_id for _, o in self._delayed_orders]).encode('utf-8') 
Example #21
Source File: dataset_reader.py    From allennlp with Apache License 2.0 5 votes vote down vote up
def serialize_instance(self, instance: Instance) -> str:
        """
        Serializes an `Instance` to a string.  We use this for caching the processed data.

        The default implementation is to use `jsonpickle`.  If you would like some other format
        for your pre-processed data, override this method.
        """
        return jsonpickle.dumps(instance) 
Example #22
Source File: plugin_firebase_stats_consumer.py    From indy-plenum with Apache License 2.0 5 votes vote down vote up
def _send(self, data: Dict[str, object]):
        self.statsPublisher.send(jsonpickle.dumps(data)) 
Example #23
Source File: base.py    From django-herald with MIT License 5 votes vote down vote up
def _get_encoded_attachments(self):
        attachments = self.get_attachments()

        new_attachments = []

        for attachment in attachments or []:
            if isinstance(attachment, File):
                # cannot do with attachment.open() since django 1.11 doesn't support that
                attachment.open()
                new_attachments.append((attachment.name, attachment.read(), guess_type(attachment.name)[0]))
                attachment.close()
            else:
                new_attachments.append(attachment)

        return jsonpickle.dumps(new_attachments)