Python simplejson.dumps() Examples

The following are code examples for showing how to use simplejson.dumps(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: jsrouting.py    Apache License 2.0 6 votes vote down vote up
def generate_adapter(adapter, name='url_for', map_name='url_map'):
    """Generates the url building function for a map."""
    values = {
        u'server_name':     dumps(adapter.server_name),
        u'script_name':     dumps(adapter.script_name),
        u'subdomain':       dumps(adapter.subdomain),
        u'url_scheme':      dumps(adapter.url_scheme),
        u'name':            name,
        u'map_name':        map_name
    }
    return u'''\
var %(name)s = %(map_name)s(
    %(server_name)s,
    %(script_name)s,
    %(subdomain)s,
    %(url_scheme)s
);''' % values 
Example 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: jsrouting.py    Apache License 2.0 6 votes vote down vote up
def generate_adapter(adapter, name='url_for', map_name='url_map'):
    """Generates the url building function for a map."""
    values = {
        u'server_name':     dumps(adapter.server_name),
        u'script_name':     dumps(adapter.script_name),
        u'subdomain':       dumps(adapter.subdomain),
        u'url_scheme':      dumps(adapter.url_scheme),
        u'name':            name,
        u'map_name':        map_name
    }
    return u'''\
var %(name)s = %(map_name)s(
    %(server_name)s,
    %(script_name)s,
    %(subdomain)s,
    %(url_scheme)s
);''' % values 
Example 3
Project: flasky   Author: RoseOu   File: jsrouting.py    MIT License 6 votes vote down vote up
def generate_adapter(adapter, name='url_for', map_name='url_map'):
    """Generates the url building function for a map."""
    values = {
        u'server_name':     dumps(adapter.server_name),
        u'script_name':     dumps(adapter.script_name),
        u'subdomain':       dumps(adapter.subdomain),
        u'url_scheme':      dumps(adapter.url_scheme),
        u'name':            name,
        u'map_name':        map_name
    }
    return u'''\
var %(name)s = %(map_name)s(
    %(server_name)s,
    %(script_name)s,
    %(subdomain)s,
    %(url_scheme)s
);''' % values 
Example 4
Project: ngo-addons-backport   Author: camptocamp   File: orm.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_modifiers(what, expected):
    modifiers = {}
    if isinstance(what, basestring):
        node = etree.fromstring(what)
        transfer_node_to_modifiers(node, modifiers)
        simplify_modifiers(modifiers)
        json = simplejson.dumps(modifiers)
        assert json == expected, "%s != %s" % (json, expected)
    elif isinstance(what, dict):
        transfer_field_to_modifiers(what, modifiers)
        simplify_modifiers(modifiers)
        json = simplejson.dumps(modifiers)
        assert json == expected, "%s != %s" % (json, expected)


# To use this test:
# import openerp
# openerp.osv.orm.modifiers_tests() 
Example 5
Project: ngo-addons-backport   Author: camptocamp   File: main.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def backup(self, req, backup_db, backup_pwd, token):
        try:
            db_dump = base64.b64decode(
                req.session.proxy("db").dump(backup_pwd, backup_db))
            filename = "%(db)s_%(timestamp)s.dump" % {
                'db': backup_db,
                'timestamp': datetime.datetime.utcnow().strftime(
                    "%Y-%m-%d_%H-%M-%SZ")
            }
            return req.make_response(db_dump,
               [('Content-Type', 'application/octet-stream; charset=binary'),
               ('Content-Disposition', content_disposition(filename, req))],
               {'fileToken': token}
            )
        except xmlrpclib.Fault, e:
            return simplejson.dumps([[],[{'error': e.faultCode, 'title': _('Backup Database')}]]) 
Example 6
Project: ngo-addons-backport   Author: camptocamp   File: http.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def dispatch(self, method):
        params = dict(self.httprequest.args)
        params.update(self.httprequest.form)
        params.update(self.httprequest.files)
        self.init(params)
        akw = {}
        for key, value in self.httprequest.args.iteritems():
            if isinstance(value, basestring) and len(value) < 1024:
                akw[key] = value
            else:
                akw[key] = type(value)
        _logger.debug("%s --> %s.%s %r", self.httprequest.method, method.im_class.__name__, method.__name__, akw)
        try:
            r = method(self, **self.params)
        except xmlrpclib.Fault, e:
            r = werkzeug.exceptions.InternalServerError(cgi.escape(simplejson.dumps({
                'code': 200,
                'message': "OpenERP Server Error",
                'data': {
                    'type': 'server_exception',
                    'fault_code': e.faultCode,
                    'debug': "Server %s\nClient %s" % (
                        e.faultString, traceback.format_exc())
                }
            }))) 
Example 7
Project: ngo-addons-backport   Author: camptocamp   File: main.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def import_url(self, req, url):
        modules = webmain.module_boot(req) + ['edi']
        modules_str = ','.join(modules)
        modules_json = simplejson.dumps(modules)
        js = "\n        ".join('<script type="text/javascript" src="%s"></script>' % i for i in webmain.manifest_list(req, modules_str, 'js'))
        css = "\n        ".join('<link rel="stylesheet" href="%s">' % i for i in webmain.manifest_list(req, modules_str, 'css'))

        # `url` may contain a full URL with a valid query string, we basically want to watch out for XML brackets and double-quotes 
        safe_url = urllib.quote_plus(url,':/?&;=')

        return webmain.html_template % {
            'js': js,
            'css': css,
            'modules': modules_json,
            'init': 's.edi.edi_import("%s");' % safe_url,
        } 
Example 8
Project: openhatch   Author: campbe13   File: jsonrpc.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __call__(self, *args):
        json = dict(method=self.name,
                    id=None,
                    params=list(args))
        req = Request.blank(self.parent._url)
        req.method = 'POST'
        req.content_type = 'application/json'
        req.body = dumps(json)
        resp = req.get_response(self.parent.proxy)
        if resp.status_code != 200 and not (
            resp.status_code == 500
            and resp.content_type == 'application/json'):
            raise ProxyError(
                "Error from JSON-RPC client %s: %s"
                % (self.parent._url, resp.status),
                resp)
        json = loads(resp.body)
        if json.get('error') is not None:
            e = Fault(
                json['error'].get('message'),
                json['error'].get('code'),
                json['error'].get('error'),
                resp)
            raise e
        return json['result'] 
Example 9
Project: thewarden   Author: pxsocs   File: routes.py    MIT License 6 votes vote down vote up
def aclst():
    list = []
    if request.method == "GET":

        tradeaccounts = Trades.query.filter_by(
            user_id=current_user.username).group_by(
            Trades.trade_account)

        accounts = AccountInfo.query.filter_by(
            user_id=current_user.username).group_by(
            AccountInfo.account_longname
        )

        q = request.args.get("term")
        for item in tradeaccounts:
            if q.upper() in item.trade_account.upper():
                list.append(item.trade_account)
        for item in accounts:
            if q.upper() in item.account_longname.upper():
                list.append(item.account_longname)

        list = json.dumps(list)

        return list 
Example 10
Project: thewarden   Author: pxsocs   File: routes.py    MIT License 6 votes vote down vote up
def fx_list():
    fx_dict = {}
    filename = 'thewarden/static/csv_files/physical_currency_list.csv'
    filename = os.path.join(current_path(), filename)
    with open(filename, newline='') as csvfile:
        reader = csv.reader(csvfile)
        fx_dict = {rows[0]: rows[1] for rows in reader}
    q = request.args.get("term")
    if q is None:
        q = ""
    list_key = {key: value for key, value in fx_dict.items() if q.upper() in key.upper()}
    list_value = {key: value for key, value in fx_dict.items() if q.upper() in value.upper()}
    list = {**list_key, **list_value}
    list = json.dumps(list)
    return list

# ------------------------------------
# API Helpers for Bitmex start here
# ------------------------------------ 
Example 11
Project: Pancas   Author: Sup3Roque   File: default.py    GNU General Public License v2.0 6 votes vote down vote up
def rmSource(name):
        ba = json.loads(open(ab,"r").read().decode('base64').decode('base64'))
        for index in range(len(ba)):
            if isinstance(ba[index], list):
                if ba[index][0] == name:
                    del ba[index]
                    b = open(ab,"w")
                    b.write(json.dumps(ba))
                    b.close()
                    break
            else:
                if ba[index]['title'] == name:
                    del ba[index]
                    b = open(ab,"w")
                    b.write(json.dumps(ba))
                    b.close()
                    break
        xbmc.executebuiltin("XBMC.Container.Refresh") 
Example 12
Project: Pancas   Author: Sup3Roque   File: default.py    GNU General Public License v2.0 6 votes vote down vote up
def kodiJsonRequest(params):
    data = json.dumps(params)
    request = xbmc.executeJSONRPC(data)

    try:
        response = json.loads(request)
    except UnicodeDecodeError:
        response = json.loads(request.decode('utf-8', 'ignore'))

    try:
        if 'result' in response:
            return response['result']
        return None
    except KeyError:
        logger.warn("[%s] %s" % (params['method'], response['error']['message']))
        return None 
Example 13
Project: Pancas   Author: Sup3Roque   File: default.py    GNU General Public License v2.0 6 votes vote down vote up
def addFavorite(name,url,iconimage,fanart,mode,playlist=None,regexs=None):
        favList = []
        try:
            # seems that after
            name = name.encode('utf-8', 'ignore')
        except:
            pass
        if os.path.exists(favorites)==False:
            addon_log('Making Favorites File')
            favList.append((name,url,iconimage,fanart,mode,playlist,regexs))
            a = open(favorites, "w")
            a.write(json.dumps(favList))
            a.close()
        else:
            addon_log('Appending Favorites')
            a = open(favorites).read()
            data = json.loads(a)
            data.append((name,url,iconimage,fanart,mode))
            b = open(favorites, "w")
            b.write(json.dumps(data))
            b.close() 
Example 14
Project: Pancas   Author: Sup3Roque   File: default.py    GNU General Public License v2.0 6 votes vote down vote up
def rmSource(name):
        ba = json.loads(open(ab,"r").read().decode('base64').decode('base64'))
        for index in range(len(ba)):
            if isinstance(ba[index], list):
                if ba[index][0] == name:
                    del ba[index]
                    b = open(ab,"w")
                    b.write(json.dumps(ba))
                    b.close()
                    break
            else:
                if ba[index]['title'] == name:
                    del ba[index]
                    b = open(ab,"w")
                    b.write(json.dumps(ba))
                    b.close()
                    break
        xbmc.executebuiltin("XBMC.Container.Refresh") 
Example 15
Project: Pancas   Author: Sup3Roque   File: default.py    GNU General Public License v2.0 6 votes vote down vote up
def addFavorite(name,url,iconimage,fanart,mode,playlist=None,regexs=None):
        favList = []
        try:
            # seems that after
            name = name.encode('utf-8', 'ignore')
        except:
            pass
        if os.path.exists(favorites)==False:
            addon_log('Making Favorites File')
            favList.append((name,url,iconimage,fanart,mode,playlist,regexs))
            a = open(favorites, "w")
            a.write(json.dumps(favList))
            a.close()
        else:
            addon_log('Appending Favorites')
            a = open(favorites).read()
            data = json.loads(a)
            data.append((name,url,iconimage,fanart,mode))
            b = open(favorites, "w")
            b.write(json.dumps(data))
            b.close() 
Example 16
Project: threat_intel   Author: Yelp   File: api_cache_test.py    MIT License 6 votes vote down vote up
def _open_cache(self, initial_contents=None, update_cache=True):
        """Creates an ApiCache object, mocking the contents of the cache on disk.

        Args:
                initial_contents: A dict containing the initial contents of the cache
                update_cache: Specifies whether ApiCache should write out the
                              cache file when closing it
        Returns:
                ApiCache
        """
        if not initial_contents:
            initial_contents = {}

        file_contents = simplejson.dumps(initial_contents)
        mock_read = mock_open(read_data=file_contents)
        with patch.object(builtins, 'open', mock_read, create=True):
            api_cache = ApiCache(self._file_name, update_cache=update_cache)
            return api_cache 
Example 17
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: jsrouting.py    Apache License 2.0 5 votes vote down vote up
def dumps(*args):
            raise RuntimeError('simplejson required for jsrouting') 
Example 18
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dumps(self, obj):
        return json.dumps(obj, separators=(',', ':')) 
Example 19
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def is_text_serializer(serializer):
    """Checks wheather a serializer generates text or binary."""
    return isinstance(serializer.dumps({}), text_type)


# Starting with 3.3 the standard library has a c-implementation for
# constant time string compares. 
Example 20
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dumps(self, obj, salt=None):
        """Returns a signed string serialized with the internal serializer.
        The return value can be either a byte or unicode string depending
        on the format of the internal serializer.
        """
        payload = want_bytes(self.dump_payload(obj))
        rv = self.make_signer(salt).sign(payload)
        if self.is_text_serializer:
            rv = rv.decode('utf-8')
        return rv 
Example 21
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dump(self, obj, f, salt=None):
        """Like :meth:`dumps` but dumps into a file.  The file handle has
        to be compatible with what the internal serializer expects.
        """
        f.write(self.dumps(obj, salt)) 
Example 22
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s)) 
Example 23
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload 
Example 24
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dump_payload(self, header, obj):
        base64d_header = base64_encode(self.serializer.dumps(header))
        base64d_payload = base64_encode(self.serializer.dumps(obj))
        return base64d_header + b'.' + base64d_payload 
Example 25
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadHeader('Algorithm mismatch', header=header,
                            payload=payload)
        if return_header:
            return payload, header
        return payload 
Example 26
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: jsrouting.py    Apache License 2.0 5 votes vote down vote up
def dumps(*args):
            raise RuntimeError('simplejson required for jsrouting') 
Example 27
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dumps(self, obj):
        return json.dumps(obj, separators=(',', ':')) 
Example 28
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dump_payload(self, obj):
        """Dumps the encoded object.  The return value is always a
        bytestring.  If the internal serializer is text based the value
        will automatically be encoded to utf-8.
        """
        return want_bytes(self.serializer.dumps(obj)) 
Example 29
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dumps(self, obj, salt=None):
        """Returns a signed string serialized with the internal serializer.
        The return value can be either a byte or unicode string depending
        on the format of the internal serializer.
        """
        payload = want_bytes(self.dump_payload(obj))
        rv = self.make_signer(salt).sign(payload)
        if self.is_text_serializer:
            rv = rv.decode('utf-8')
        return rv 
Example 30
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dump(self, obj, f, salt=None):
        """Like :meth:`dumps` but dumps into a file.  The file handle has
        to be compatible with what the internal serializer expects.
        """
        f.write(self.dumps(obj, salt)) 
Example 31
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s)) 
Example 32
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload 
Example 33
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def dumps(self, obj, salt=None, header_fields=None):
        """Like :meth:`~Serializer.dumps` but creates a JSON Web Signature.  It
        also allows for specifying additional fields to be included in the JWS
        Header.
        """
        header = self.make_header(header_fields)
        signer = self.make_signer(salt, self.algorithm)
        return signer.sign(self.dump_payload(header, obj)) 
Example 34
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadHeader('Algorithm mismatch', header=header,
                            payload=payload)
        if return_header:
            return payload, header
        return payload 
Example 35
Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    Apache License 2.0 5 votes vote down vote up
def json(self, pretty=False):
		"""Return data in JSON format"""

		kwargs = {}
		if pretty:
			kwargs.update({
				'indent': 4,
				'sort_keys': True
			})
		return json.dumps(self.dict(), **kwargs) 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sensu_silence.py    MIT License 5 votes vote down vote up
def query(module, url, check, subscription):
    headers = {
        'Content-Type': 'application/json',
    }

    url = url + '/silenced'

    request_data = {
        'check': check,
        'subscription': subscription,
    }

    # Remove keys with None value
    for k, v in dict(request_data).items():
        if v is None:
            del request_data[k]

    response, info = fetch_url(
        module, url, method='GET',
        headers=headers, data=json.dumps(request_data)
    )

    if info['status'] == 500:
        module.fail_json(
            msg="Failed to query silence %s. Reason: %s" % (subscription, info)
        )

    try:
        json_out = json.loads(response.read())
    except:
        json_out = ""

    return False, json_out, False 
Example 37
Project: flasky   Author: RoseOu   File: jsrouting.py    MIT License 5 votes vote down vote up
def dumps(*args):
            raise RuntimeError('simplejson required for jsrouting') 
Example 38
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def dumps(self, obj):
        return json.dumps(obj, separators=(',', ':')) 
Example 39
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def is_text_serializer(serializer):
    """Checks wheather a serializer generates text or binary."""
    return isinstance(serializer.dumps({}), text_type)


# Starting with 3.3 the standard library has a c-implementation for
# constant time string compares. 
Example 40
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def dumps(self, obj, salt=None):
        """Returns a signed string serialized with the internal serializer.
        The return value can be either a byte or unicode string depending
        on the format of the internal serializer.
        """
        payload = want_bytes(self.dump_payload(obj))
        rv = self.make_signer(salt).sign(payload)
        if self.is_text_serializer:
            rv = rv.decode('utf-8')
        return rv 
Example 41
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def dump(self, obj, f, salt=None):
        """Like :meth:`dumps` but dumps into a file.  The file handle has
        to be compatible with what the internal serializer expects.
        """
        f.write(self.dumps(obj, salt)) 
Example 42
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s)) 
Example 43
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload 
Example 44
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def dump_payload(self, header, obj):
        base64d_header = base64_encode(self.serializer.dumps(header))
        base64d_payload = base64_encode(self.serializer.dumps(obj))
        return base64d_header + b'.' + base64d_payload 
Example 45
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadSignature('Algorithm mismatch')
        if return_header:
            return payload, header
        return payload 
Example 46
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: xenstore.py    Apache License 2.0 5 votes vote down vote up
def jsonify(fnc):
    def wrapper(*args, **kwargs):
        ret = fnc(*args, **kwargs)
        try:
            json.loads(ret)
        except ValueError:
            # Value should already be JSON-encoded, but some operations
            # may write raw sting values; this will catch those and
            # properly encode them.
            ret = json.dumps(ret)
        return ret
    return wrapper 
Example 47
Project: ansible-playbook-okd-install-kvm   Author: Jooho   File: kvm.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    args = parse_args()
    connection = create_connection()

    print(
        json.dumps(
            obj=get_data(
                connection=connection,
                target_vm_name=args.host,
            ),
            sort_keys=args.pretty,
            indent=args.pretty * 2,
        )
    ) 
Example 48
Project: Parallel.GAMIT   Author: demiangomez   File: pyBunch.py    GNU General Public License v3.0 5 votes vote down vote up
def toJSON(self, **options):
        """ Serializes this Bunch to JSON. Accepts the same keyword options as `json.dumps()`.

            >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')
            >>> json.dumps(b)
            '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'
            >>> b.toJSON()
            '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'
        """
        return json.dumps(self, **options) 
Example 49
Project: wemoo-center   Author: wemoo   File: log_test.py    MIT License 5 votes vote down vote up
def test_create_one_log(self):
        app_id = 'test-app-id'
        level = 'info'
        log_type = 'test-type'
        content = {'level1_1': 1, 'level1_2': {'leve2_1': 1}}
        data = {'app_id': app_id, 'level': level, 'log_type': log_type, 'content': content}

        url = '/api/logs'
        res = self.test.post(url, data=simplejson.dumps(data))
        assert res.status_code == 200
        assert simplejson.loads(res.data)['status'] == 'ok' 
Example 50
Project: ngo-addons-backport   Author: camptocamp   File: fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _symbol_set_struct(val):
        return simplejson.dumps(val)