本文整理汇总了Python中util.json.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: submit
def submit(self, metrics):
# HACK - Copy and pasted from dogapi, because it's a bit of a pain to distribute python
# dependencies with the agent.
body = json.dumps({"series" : metrics})
headers = {'Content-Type':'application/json'}
method = 'POST'
params = {}
if self.api_key:
params['api_key'] = self.api_key
url = '/api/v1/series?%s' % urlencode(params)
start_time = time()
status = None
conn = self.http_conn_cls(self.api_host)
try:
conn.request(method, url, body, headers)
#FIXME: add timeout handling code here
response = conn.getresponse()
status = response.status
response.close()
finally:
conn.close()
duration = round((time() - start_time) * 1000.0, 4)
log.debug("%s %s %s%s (%sms)" % (
status, method, self.api_host, url, duration))
return duration
开发者ID:mikery,项目名称:dd-agent,代码行数:29,代码来源:dogstatsd.py
示例2: emit_many
def emit_many(self, tuples, stream=None, anchors=[], direct_task=None):
"""A more efficient way to send many tuples, dumps out all tuples to
STDOUT instead of writing one at a time.
:param tuples: an iterable of ``list``s representing the tuples to send
to Storm. All tuples should contain only JSON-serializable data.
:param stream: a ``str`` indicating the ID of the steram to emit these
tuples to. Specify ``None`` to emit to default stream.
:param anchors: a `` list`` of IDs the tuples these tuples should be
anchored to.
:param direct_task: an ``int`` which indicates the task to send the
tuple to.
"""
if _ANCHOR_TUPLE is not None:
anchors = [_ANCHOR_TUPLE]
msg = {
'command': 'emit',
'anchors': [a.id for a in anchors],
}
if stream is not None:
msg['stream'] = stream
if direct_task is not None:
msg['task'] = direct_task
lines = []
for tup in tuples:
msg['tuple'] = tup
lines.append(json.dumps(msg))
lines.append('end')
print('\n'.join(lines), file=_stdout)
开发者ID:Snazz2001,项目名称:streamparse,代码行数:30,代码来源:bolt.py
示例3: _postMetrics
def _postMetrics(self):
if len(self._metrics) > 0:
self._metrics["uuid"] = get_uuid()
self._metrics["internalHostname"] = get_hostname(self._agentConfig)
self._metrics["apiKey"] = self._agentConfig["api_key"]
MetricTransaction(json.dumps(self._metrics), headers={"Content-Type": "application/json"})
self._metrics = {}
开发者ID:miketheman,项目名称:dd-agent,代码行数:8,代码来源:ddagent.py
示例4: _postMetrics
def _postMetrics(self):
if len(self._metrics) > 0:
self._metrics['uuid'] = get_uuid()
self._metrics['internalHostname'] = get_hostname(self._agentConfig)
self._metrics['apiKey'] = self._agentConfig['api_key']
MetricTransaction(json.dumps(self._metrics),
headers={'Content-Type': 'application/json'})
self._metrics = {}
开发者ID:DavidXArnold,项目名称:dd-agent,代码行数:9,代码来源:ddagent.py
示例5: serialize_metrics
def serialize_metrics(metrics):
serialized = json.dumps({"series" : metrics})
if len(serialized) > COMPRESS_THRESHOLD:
headers = {'Content-Type': 'application/json',
'Content-Encoding': 'deflate'}
serialized = zlib.compress(serialized)
else:
headers = {'Content-Type': 'application/json'}
return serialized, headers
开发者ID:arthurnn,项目名称:dd-agent,代码行数:9,代码来源:dogstatsd.py
示例6: renderPackets
def renderPackets(self, packets=None):
if packets is None:
packets = self.buffer
if self.permVars['se']:
sseid = "\r\n"
else:
sseid = ""
if self.permVars["se"] and packets:
sseid = "id: %s\r\n\r\n"%(packets[-1][0],)
return "%s(%s)%s%s"%(self.permVars["bp"], json.dumps(packets), self.permVars["bs"], sseid)
开发者ID:skysbird,项目名称:csp,代码行数:10,代码来源:session.py
示例7: members
def members():
all_users = user_server.get_list(limit=-1)
users = []
for user in all_users:
if user.is_student:
users.append({
'name': user.name,
'college': SCHOOL_COLLEGE_MAP[user.college] if user.college else '',
'grade': user.grade + u'级' if user.grade else '',
'situation': user.situation
})
return json.dumps({ 'data': users })
开发者ID:WiseFoolC,项目名称:CUIT-ACM-Website,代码行数:12,代码来源:ajax.py
示例8: recent_contests
def recent_contests():
import json
json_file = open(RECENT_CONTEST_JSON, 'r').read()
json_contests = json.JSONDecoder().decode(json_file)
contests = []
for contest in json_contests:
name, link = contest['name'], contest['link']
new_contest = {
'oj': contest['oj'],
'name': '<a href="' + link + '" class="contest-name" title="' + name + '">' + name + '</a>',
'start_time': contest['start_time'],
'access': contest['access'],
}
contests.append(new_contest)
return json.dumps({ 'data': contests })
开发者ID:WiseFoolC,项目名称:CUIT-ACM-Website,代码行数:15,代码来源:ajax.py
示例9: request_params
def request_params(self, url, method, **kwargs):
"""
Constructs the parameters for a http request
"""
params = dict()
if self._access_key is not None:
params['access_key'] = self._access_key
if kwargs:
params.update(kwargs)
if method == "GET":
url = url + "?" + urllib.urlencode(params, doseq=True)
body = None
else:
body = json.dumps(params, cls=EasyPeasyJsonEncoder)
return url, method, body, _def_headers
开发者ID:kochhar,项目名称:pyrabj,代码行数:18,代码来源:api.py
示例10: submit
def submit(self, metrics):
# HACK - Copy and pasted from dogapi, because it's a bit of a pain to distribute python
# dependencies with the agent.
conn = self.http_conn_cls(self.api_host)
body = json.dumps({"series": metrics})
headers = {"Content-Type": "application/json"}
method = "POST"
params = {}
if self.api_key:
params["api_key"] = self.api_key
url = "/api/v1/series?%s" % urlencode(params)
start_time = time.time()
conn.request(method, url, body, headers)
# FIXME: add timeout handling code here
response = conn.getresponse()
duration = round((time.time() - start_time) * 1000.0, 4)
logger.info("%s %s %s%s (%sms)" % (response.status, method, self.api_host, url, duration))
开发者ID:SafPlusPlus,项目名称:dd-agent,代码行数:22,代码来源:dogstatsd.py
示例11: update
def update(self, value):
"""Update the config
Parameters:
value The config value
Returns:
Nothing
"""
if not isinstance(value, dict):
self.logger.error("[%s] Failed to update config, value must be a dict", self.Type)
return False
# Validate
try:
self.validate(value)
except:
self.logger.exception("[%s] Failed to validate config value: [%s]", self.Type, json.dumps(value, ensure_ascii = False))
return False
# Remove all values from self and update new values
def updateConfig():
"""Update the config
"""
self.clear()
super(ConfigSection, self).update(value)
self._timestamp = time.time()
# Update
if self._reloadLock:
with self._reloadLock:
updateConfig()
else:
updateConfig()
# If reload is required
if self.ReloadRequired:
self._reloadEvent.set()
# Updated
self._updatedEvent.set()
if self.logger.isEnabledFor(logging.DEBUG):
self.logger.debug("[%s] Config updated [%s]", self.Type, json.dumps(value, ensure_ascii = False))
# Done
return True
开发者ID:lipixun,项目名称:pyconfigmslib,代码行数:38,代码来源:section.py
示例12: http_emitter
def http_emitter(message, log, agentConfig):
"Send payload"
log.debug('http_emitter: attempting postback to ' + agentConfig['dd_url'])
# Post back the data
payload = json.dumps(message)
zipped = zlib.compress(payload)
log.debug("payload_size=%d, compressed_size=%d, compression_ratio=%.3f" % (len(payload), len(zipped), float(len(payload))/float(len(zipped))))
# Build the request handler
apiKey = message.get('apiKey', None)
if not apiKey:
raise Exception("The http emitter requires an api key")
url = "%s/intake?api_key=%s" % (agentConfig['dd_url'], apiKey)
headers = post_headers(agentConfig, zipped)
proxy_settings = agentConfig.get('proxy_settings', None)
urllib2 = get_http_library(proxy_settings, agentConfig['use_forwarder'])
try:
request = urllib2.Request(url, zipped, headers)
# Do the request, log any errors
opener = get_opener(log, proxy_settings, agentConfig['use_forwarder'], urllib2)
if opener is not None:
urllib2.install_opener(opener)
response = urllib2.urlopen(request)
try:
log.debug('http_emitter: postback response: ' + str(response.read()))
finally:
response.close()
except urllib2.HTTPError, e:
if e.code == 202:
log.debug("http payload accepted")
else:
raise
开发者ID:Tokutek,项目名称:dd-agent,代码行数:38,代码来源:emitter.py
示例13: submit_events
def submit_events(self, events):
headers = {'Content-Type':'application/json'}
method = 'POST'
events_len = len(events)
event_chunk_size = self.event_chunk_size
for chunk in chunks(events, event_chunk_size):
payload = {
'apiKey': self.api_key,
'events': {
'api': chunk
},
'uuid': get_uuid(),
'internalHostname': get_hostname()
}
params = {}
if self.api_key:
params['api_key'] = self.api_key
url = '/intake?%s' % urlencode(params)
status = None
conn = self.http_conn_cls(self.api_host)
try:
start_time = time()
conn.request(method, url, json.dumps(payload), headers)
response = conn.getresponse()
status = response.status
response.close()
duration = round((time() - start_time) * 1000.0, 4)
log.debug("%s %s %s%s (%sms)" % (
status, method, self.api_host, url, duration))
finally:
conn.close()
开发者ID:dhapgood4thscreen,项目名称:dd-agent,代码行数:36,代码来源:dogstatsd.py
示例14: format_body
def format_body(message, logger):
payload = json.dumps(message)
payloadHash = md5(payload).hexdigest()
postBackData = urllib.urlencode({'payload' : payload, 'hash' : payloadHash})
return postBackData
开发者ID:FriedWishes,项目名称:dd-agent,代码行数:5,代码来源:emitter.py
示例15: serialize_event
def serialize_event(event):
return json.dumps(event)
开发者ID:dhapgood4thscreen,项目名称:dd-agent,代码行数:2,代码来源:dogstatsd.py
示例16: serialize_metrics
def serialize_metrics(metrics):
return json.dumps({"series" : metrics})
开发者ID:dhapgood4thscreen,项目名称:dd-agent,代码行数:2,代码来源:dogstatsd.py
示例17: fitch_status
def fitch_status(oj_name):
headers = ['account_name', 'run_id', 'pro_id', 'lang', 'run_time', 'memory', 'submit_time']
ret = status_server.DataTablesServer(request.form, oj_name, headers).run_query()
return json.dumps(ret, cls=CJsonEncoder)
开发者ID:WiseFoolC,项目名称:CUIT-ACM-Website,代码行数:4,代码来源:ajax.py
示例18: renderRequest
def renderRequest(self, data, request):
request.setHeader('Content-type', self.permVars['ct'])
x = self.tryCompress("%s(%s)%s"%(self.permVars["rp"], json.dumps(data), self.permVars["rs"]), request)
return x
开发者ID:skysbird,项目名称:csp,代码行数:4,代码来源:session.py
示例19: main_rank_table
def main_rank_table():
main_rank_list = general.get_rank_list()
return json.dumps({ 'data': main_rank_list })
开发者ID:WiseFoolC,项目名称:CUIT-ACM-Website,代码行数:3,代码来源:ajax.py
示例20: write_json
def write_json(self, data, status_code=200, msg='success.'):
self.finish(dumps({
'code': status_code,
'msg': msg,
'data': data
}))
开发者ID:INAP-LABS,项目名称:noc-orchestrator,代码行数:6,代码来源:base.py
注:本文中的util.json.dumps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论