本文整理汇总了Python中requests.compat.json.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: clientresp
def clientresp(data, **kwargs):
"""
Deprecated endpoint, still used because it can parse data out of a plot.
When we get around to forcing users to create grids and then create plots,
we can finally get rid of this.
:param (list) data: The data array from a figure.
"""
creds = config.get_credentials()
cfg = config.get_config()
dumps_kwargs = {'sort_keys': True, 'cls': utils.PlotlyJSONEncoder}
payload = {
'platform': 'python', 'version': version.stable_semver(),
'args': _json.dumps(data, **dumps_kwargs),
'un': creds['username'], 'key': creds['api_key'], 'origin': 'plot',
'kwargs': _json.dumps(kwargs, **dumps_kwargs)
}
url = '{plotly_domain}/clientresp'.format(**cfg)
response = request('post', url, data=payload)
# Old functionality, just keeping it around.
parsed_content = response.json()
if parsed_content.get('warning'):
warnings.warn(parsed_content['warning'])
if parsed_content.get('message'):
print(parsed_content['message'])
return response
开发者ID:codybushnell,项目名称:plotly.py,代码行数:33,代码来源:clientresp.py
示例2: test_masked_constants_example
def test_masked_constants_example():
# example from: https://gist.github.com/tschaume/d123d56bf586276adb98
data = {
'esN': [0, 1, 2, 3],
'ewe_is0': [-398.11901997, -398.11902774,
-398.11897111, -398.11882215],
'ewe_is1': [-398.11793027, -398.11792966, -398.11786308, None],
'ewe_is2': [-398.11397008, -398.11396421, None, None]
}
df = pd.DataFrame.from_dict(data)
plotopts = {'x': 'esN'}
fig, ax = plt.subplots(1, 1)
df.plot(ax=ax, **plotopts)
renderer = PlotlyRenderer()
Exporter(renderer).run(fig)
_json.dumps(renderer.plotly_fig, cls=utils.PlotlyJSONEncoder)
jy = _json.dumps(renderer.plotly_fig['data'][1]['y'],
cls=utils.PlotlyJSONEncoder)
print(jy)
array = _json.loads(jy)
assert(array == [-398.11793027, -398.11792966, -398.11786308, None])
开发者ID:codybushnell,项目名称:plotly.py,代码行数:25,代码来源:test_utils.py
示例3: test_data_to_json
def test_data_to_json(self):
"""
Tests that data_to_json serializes dicts / objects / models to json
"""
from rubber.instanceutils import data_to_json
# with a dict
data = {'foo':'bar'}
json_data = json.dumps(data)
self.assertEquals(json_data, data_to_json(data))
# with a string
json_data = json.dumps(data)
self.assertEquals(json_data, data_to_json(json_data))
# try a class that implements to_indexed_json
class Foo(object):
def to_indexed_json(self):
return json_data
self.assertEquals(json_data, data_to_json(Foo()))
# try a django model
try:
from django.db import models
class TestModel(models.Model):
foo = models.CharField(max_length=3)
bar = TestModel(foo='bar')
self.assertEquals(json_data, data_to_json(bar))
except ImportError:
pass
开发者ID:mazandaran,项目名称:rubber,代码行数:31,代码来源:alltests.py
示例4: test_datetime_json_encoding
def test_datetime_json_encoding():
j1 = _json.dumps(dt_list, cls=utils.PlotlyJSONEncoder)
assert(j1 == '["2014-01-05", '
'"2014-01-05 01:01:01", '
'"2014-01-05 01:01:01.000001"]')
j2 = _json.dumps({"x": dt_list}, cls=utils.PlotlyJSONEncoder)
assert(j2 == '{"x": ["2014-01-05", '
'"2014-01-05 01:01:01", '
'"2014-01-05 01:01:01.000001"]}')
开发者ID:codybushnell,项目名称:plotly.py,代码行数:9,代码来源:test_utils.py
示例5: test_col_create
def test_col_create(self):
cols = [
{'name': 'foo', 'data': [1, 2, 3]},
{'name': 'bar', 'data': ['b', 'a', 'r']},
]
body = {'cols': _json.dumps(cols, sort_keys=True)}
grids.col_create('hodor:88', body)
assert self.request_mock.call_count == 1
args, kwargs = self.request_mock.call_args
method, url = args
self.assertEqual(method, 'post')
self.assertEqual(
url, '{}/v2/grids/hodor:88/col'.format(self.plotly_api_domain)
)
self.assertEqual(kwargs['data'], _json.dumps(body, sort_keys=True))
开发者ID:codybushnell,项目名称:plotly.py,代码行数:15,代码来源:test_grids.py
示例6: _handle_outgoing_message
def _handle_outgoing_message(self, message):
if self._graphId == '':
self._clientMessages.append(message)
else:
message['graphId'] = self._graphId
message['uid'] = str(uuid.uuid4())
self._message = _json.dumps(message, cls=utils.PlotlyJSONEncoder)
开发者ID:fcolmenero,项目名称:plotly.py,代码行数:7,代码来源:graph_widget.py
示例7: _request
def _request(self, verb, path="/", data=None):
url = "%s%s" % (API_URL, path)
if data is not None:
data = json.dumps(data)
response = self._session.request(verb, url,
allow_redirects=False,
data=data)
if response.status_code == 200:
return response.json()
if response.status_code == 401:
raise AuthorizationError(response)
if response.status_code != 307:
raise APIError(response)
redirect_url = response.headers['Location']
response = self._session.request(verb, redirect_url,
allow_redirects=False,
data=data)
# TODO check for 429 status code for too frequent access.
# see https://developers.nest.com/documentation/cloud/data-rate-limits
if 400 <= response.status_code < 600:
raise APIError(response)
return response.json()
开发者ID:WisdomWolf,项目名称:python-nest,代码行数:28,代码来源:nest.py
示例8: request
def request(self, method, url, body=None, header={}):
url = url if url.lower().startswith('https://') else self.API_ENDPOINT + url
params = {}
if isinstance(body, dict):
if body:
# Dump without whitespace.
params['headers'] = {'Content-Type': 'application/json'}
params['data'] = json.dumps(body, separators=(',', ':'))
elif body:
params['data'] = body
try:
response = self.session.request(method, url, **params)
except requests.exceptions.Timeout as err:
raise ConnectionError('Timeout while connecting', cause=err)
except Exception as err:
raise ConnectionError('Error while connecting: {0}'.format(err), cause=err)
count = response.headers.get('compression-count')
if count:
tinify.compression_count = int(count)
if response.ok:
return response
else:
details = None
try:
details = response.json()
except Exception as err:
details = {'message': 'Error while parsing response: {0}'.format(err), 'error': 'ParseError'}
raise Error.create(details.get('message'), details.get('error'), response.status_code)
开发者ID:ajparsons,项目名称:tinify-python,代码行数:31,代码来源:client.py
示例9: test_validate_json_content_dict_error_empty
def test_validate_json_content_dict_error_empty(self):
content = self.to_bytes(_json.dumps({'error': ''}))
response = self.get_response(content=content, status_code=200)
try:
utils.validate_response(response)
except PlotlyRequestError:
self.fail('Expected this not to raise!')
开发者ID:fcolmenero,项目名称:plotly.py,代码行数:7,代码来源:test_utils.py
示例10: test_col_update
def test_col_update(self):
cols = [
{'name': 'foo', 'data': [1, 2, 3]},
{'name': 'bar', 'data': ['b', 'a', 'r']},
]
body = {'cols': _json.dumps(cols, sort_keys=True)}
grids.col_update('hodor:88', 'aaaaaa,bbbbbb', body)
self.request_mock.assert_called_once()
args, kwargs = self.request_mock.call_args
method, url = args
self.assertEqual(method, 'put')
self.assertEqual(
url, '{}/v2/grids/hodor:88/col'.format(self.plotly_api_domain)
)
self.assertEqual(kwargs['params'], {'uid': 'aaaaaa,bbbbbb'})
self.assertEqual(kwargs['data'], _json.dumps(body, sort_keys=True))
开发者ID:fcolmenero,项目名称:plotly.py,代码行数:16,代码来源:test_grids.py
示例11: encode
def encode(self, o):
"""
Load and then dump the result using parse_constant kwarg
Note that setting invalid separators will cause a failure at this step.
"""
# this will raise errors in a normal-expected way
encoded_o = super(PlotlyJSONEncoder, self).encode(o)
# now:
# 1. `loads` to switch Infinity, -Infinity, NaN to None
# 2. `dumps` again so you get 'null' instead of extended JSON
try:
new_o = _json.loads(encoded_o,
parse_constant=self.coerce_to_strict)
except ValueError:
# invalid separators will fail here. raise a helpful exception
raise ValueError(
"Encoding into strict JSON failed. Did you set the separators "
"valid JSON separators?"
)
else:
return _json.dumps(new_o, sort_keys=self.sort_keys,
indent=self.indent,
separators=(self.item_separator,
self.key_separator))
开发者ID:fu,项目名称:plotly.py,代码行数:29,代码来源:utils.py
示例12: _set
def _set(self, what, data):
url = '%s/v2/put/%s.%s' % (self._nest_api.urls['transport_url'],
what, self._serial)
response = self._nest_api._session.post(url, data=json.dumps(data))
response.raise_for_status()
self._nest_api._bust_cache()
开发者ID:bsmithyman,项目名称:nest_thermostat,代码行数:7,代码来源:nest.py
示例13: _to_binary
def _to_binary(body):
from requests.compat import json as complexjson
data = complexjson.dumps(body)
if not isinstance(data, bytes):
return data.encode('utf-8')
else:
return data
开发者ID:huntzhan,项目名称:img2url,代码行数:7,代码来源:github.py
示例14: upload_permanent_video
def upload_permanent_video(self, title, introduction, video):
"""
上传永久视频。
:param title: 视频素材的标题
:param introduction: 视频素材的描述
:param video: 要上传的视频,一个 File-object
:return: requests 的 Response 实例
"""
return requests.post(
url="https://api.weixin.qq.com/cgi-bin/material/add_material",
params={
"access_token": self.token,
"type": "video"
},
data={
"description": _json.dumps({
"title": title,
"introduction": introduction
}, ensure_ascii=False).encode("utf-8")
},
files={
"media": video
}
)
开发者ID:adam139,项目名称:WeRobot,代码行数:25,代码来源:client.py
示例15: test_default_plot_generates_expected_html
def test_default_plot_generates_expected_html(self):
data_json = _json.dumps(fig['data'],
cls=plotly.utils.PlotlyJSONEncoder)
layout_json = _json.dumps(
fig['layout'],
cls=plotly.utils.PlotlyJSONEncoder)
html = self._read_html(plotly.offline.plot(fig, auto_open=False))
# I don't really want to test the entire script output, so
# instead just make sure a few of the parts are in here?
self.assertIn('Plotly.newPlot', html) # plot command is in there
self.assertIn(data_json, html) # data is in there
self.assertIn(layout_json, html) # so is layout
self.assertIn(PLOTLYJS, html) # and the source code
# and it's an <html> doc
self.assertTrue(html.startswith('<html>') and html.endswith('</html>'))
开发者ID:fcolmenero,项目名称:plotly.py,代码行数:17,代码来源:test_offline.py
示例16: _prep_request
def _prep_request(self, body):
"""
Encodes body as json.
"""
try:
return json.dumps(body)
except (TypeError, json.JSONDecodeError), e:
raise ElasticSearchError('Invalid JSON %r' % (body,), e)
开发者ID:acdha,项目名称:pyelasticsearch,代码行数:8,代码来源:pyelasticsearch.py
示例17: __str__
def __str__(self):
max_chars = 10
jdata = _json.dumps(self.data, cls=utils.PlotlyJSONEncoder)
if len(jdata) > max_chars:
data_string = jdata[:max_chars] + "...]"
else:
data_string = jdata
string = '<name="{name}", data={data_string}, id={id}>'
return string.format(name=self.name, data=data_string, id=self.id)
开发者ID:fcolmenero,项目名称:plotly.py,代码行数:9,代码来源:grid_objs.py
示例18: create
def create(cls, name, remotefs, server,
num_executors=2,
node_description=None,
labels=None,
exclusive=False,
launcher=NodeLaunchMethod.COMMAND,
launcher_params={}):
'''
:param name: name of node to create, ``str``
:param remotefs: Remote root directory, ``str``
:param num_executors: number of executors for node, ``int``
:param node_description: Description of node, ``str``
:param labels: Labels to associate with node, ``str``
:param exclusive: Use this node for tied jobs only, ``bool``
:param launcher: Slave launch method, ``NodeLaunchMethod|str``
:param launcher_params: Additional launcher parameters, ``dict``
'''
node = cls(name, server)
if node.exists:
raise JenkinsError('node "%s" already exists' % name)
mode = 'EXCLUSIVE' if exclusive else 'NORMAL'
launcher_params['stapler-class'] = launcher
# Note that CommandLauncher class removed from Jenkins core in 2.86.
# It is now available in the command-launcher plugin.
inner_params = {
'name': name,
'nodeDescription': node_description,
'numExecutors': num_executors,
'remoteFS': remotefs,
'labelString': labels,
'mode': mode,
'type': 'hudson.slaves.DumbSlave$DescriptorImpl',
'retentionStrategy': {
'stapler-class':
'hudson.slaves.RetentionStrategy$Always'
},
'nodeProperties': {'stapler-class-bag': 'true'},
'launcher': launcher_params
}
params = {
'name': name,
'type': 'hudson.slaves.DumbSlave$DescriptorImpl',
'json': json.dumps(inner_params)
}
res = server.post('computer/doCreateItem', params=params, throw=False)
if not res or res.status_code != 200:
print(res.text)
raise JenkinsError('create "%s" failed' % name)
else:
res.raise_for_status()
开发者ID:gvalkov,项目名称:jenkins-webapi,代码行数:56,代码来源:jenkins.py
示例19: test_row
def test_row(self):
body = {'rows': [[1, 'A'], [2, 'B']]}
grids.row('hodor:88', body)
assert self.request_mock.call_count == 1
args, kwargs = self.request_mock.call_args
method, url = args
self.assertEqual(method, 'post')
self.assertEqual(
url, '{}/v2/grids/hodor:88/row'.format(self.plotly_api_domain)
)
self.assertEqual(kwargs['data'], _json.dumps(body, sort_keys=True))
开发者ID:codybushnell,项目名称:plotly.py,代码行数:11,代码来源:test_grids.py
示例20: save_json_dict
def save_json_dict(filename, json_dict):
"""Save json to file. Error if path DNE, not a dict, or invalid json."""
if isinstance(json_dict, dict):
# this will raise a TypeError if something goes wrong
json_string = _json.dumps(json_dict, indent=4)
lock.acquire()
with open(filename, "w") as f:
f.write(json_string)
lock.release()
else:
raise TypeError("json_dict was not a dictionary. not saving.")
开发者ID:fu,项目名称:plotly.py,代码行数:11,代码来源:utils.py
注:本文中的requests.compat.json.dumps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论