本文整理汇总了Python中requests.compat.json.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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])
示例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
示例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"]}')
示例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))
示例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)
示例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()
示例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)
示例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!')
示例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))
示例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))
示例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()
示例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
示例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
}
)
示例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>'))