本文整理匯總了Python中simplejson.dumps方法的典型用法代碼示例。如果您正苦於以下問題:Python simplejson.dumps方法的具體用法?Python simplejson.dumps怎麽用?Python simplejson.dumps使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類simplejson
的用法示例。
在下文中一共展示了simplejson.dumps方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: aclst
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
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
示例2: fx_list
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
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
# ------------------------------------
示例3: _open_cache
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
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
示例4: encrypt
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def encrypt(self, message):
"""Method for encrypting data.
This method takes plaintext as input and returns encrypted data.
This need not be called directly as enncryption/decryption is
taken care of transparently by Pubnub class if cipher key is
provided at time of initializing pubnub object
Args:
message: Message to be encrypted.
Returns:
Returns encrypted message if cipher key is set
"""
if self.cipher_key:
message = json.dumps(self.pc.encrypt(
self.cipher_key, json.dumps(message)).replace('\n', ''))
else:
message = json.dumps(message)
return message
示例5: analyze
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def analyze(self):
ctxt = PyV8.JSContext()
ctxt.enter()
f1 = open(os.path.join(self.file_dir, 'js/wappalyzer.js'))
f2 = open(os.path.join(self.file_dir, '../php/js/driver.js'))
ctxt.eval(f1.read())
ctxt.eval(f2.read())
f1.close()
f2.close()
host = urlparse(self.url).hostname
response = requests.get(self.url)
html = response.text
headers = dict(response.headers)
data = {'host': host, 'url': self.url, 'html': html, 'headers': headers}
apps = json.dumps(self.apps)
categories = json.dumps(self.categories)
return ctxt.eval("w.apps = %s; w.categories = %s; w.driver.data = %s; w.driver.init();" % (apps, categories, json.dumps(data)))
示例6: convert
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def convert(self, topic, body):
try:
self.dict_result["deviceName"] = topic.split("/")[-1] # getting all data after last '/' symbol in this case: if topic = 'devices/temperature/sensor1' device name will be 'sensor1'.
self.dict_result["deviceType"] = "Thermostat" # just hardcode this
self.dict_result["telemetry"] = [] # template for telemetry array
bytes_to_read = body.replace("0x", "") # Replacing the 0x (if '0x' in body), needs for converting to bytearray
converted_bytes = bytearray.fromhex(bytes_to_read) # Converting incoming data to bytearray
if self.__config.get("extension-config") is not None:
for telemetry_key in self.__config["extension-config"]: # Processing every telemetry key in config for extension
value = 0
for _ in range(self.__config["extension-config"][telemetry_key]): # reading every value with value length from config
value = value*256 + converted_bytes.pop(0) # process and remove byte from processing
telemetry_to_send = {telemetry_key.replace("Bytes", ""): value} # creating telemetry data for sending into Thingsboard
self.dict_result["telemetry"].append(telemetry_to_send) # adding data to telemetry array
else:
self.dict_result["telemetry"] = {"data": int(body, 0)} # if no specific configuration in config file - just send data which received
return self.dict_result
except Exception as e:
log.exception('Error in converter, for config: \n%s\n and message: \n%s\n', dumps(self.__config), body)
log.exception(e)
示例7: send_rpc_reply
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def send_rpc_reply(self, device=None, req_id=None, content=None, success_sent=None, wait_for_publish=None, quality_of_service=0):
try:
self.__rpc_reply_sent = True
rpc_response = {"success": False}
if success_sent is not None:
if success_sent:
rpc_response["success"] = True
if device is not None and success_sent is not None:
self.tb_client.client.gw_send_rpc_reply(device, req_id, dumps(rpc_response), quality_of_service=quality_of_service)
elif device is not None and req_id is not None and content is not None:
self.tb_client.client.gw_send_rpc_reply(device, req_id, content, quality_of_service=quality_of_service)
elif device is None and success_sent is not None:
self.tb_client.client.send_rpc_reply(req_id, dumps(rpc_response), quality_of_service=quality_of_service, wait_for_publish=wait_for_publish)
elif device is None and content is not None:
self.tb_client.client.send_rpc_reply(req_id, content, quality_of_service=quality_of_service, wait_for_publish=wait_for_publish)
self.__rpc_reply_sent = False
except Exception as e:
log.exception(e)
示例8: send_current_configuration
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def send_current_configuration(self):
try:
current_configuration = {}
for connector in self.__gateway.connectors_configs:
if current_configuration.get(connector) is None:
current_configuration[connector] = []
for config in self.__gateway.connectors_configs[connector]:
for config_file in config['config']:
current_configuration[connector].append({'name': config['name'], 'config': config['config'][config_file]})
current_configuration["thingsboard"] = self.__old_general_configuration_file
current_configuration["thingsboard"]["logs"] = b64encode(self.__old_logs_configuration.replace('\n', '}}').encode("UTF-8"))
json_current_configuration = dumps(current_configuration)
encoded_current_configuration = b64encode(json_current_configuration.encode())
self.__old_configuration = encoded_current_configuration
self.__gateway.tb_client.client.send_attributes(
{"current_configuration": encoded_current_configuration.decode("UTF-8")})
LOG.debug('Current configuration has been sent to ThingsBoard: %s', json_current_configuration)
except Exception as e:
LOG.exception(e)
示例9: __request_attributes
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def __request_attributes(self, device, keys, callback, type_is_client=False):
if not keys:
log.error("There are no keys to request")
return False
keys_str = ""
for key in keys:
keys_str += key + ","
keys_str = keys_str[:len(keys_str) - 1]
ts_in_millis = int(round(time.time() * 1000))
attr_request_number = self._add_attr_request_callback(callback)
msg = {"key": keys_str,
"device": device,
"client": type_is_client,
"id": attr_request_number}
info = self._client.publish(GATEWAY_ATTRIBUTES_REQUEST_TOPIC, dumps(msg), 1)
self._add_timeout(attr_request_number, ts_in_millis + 30000)
return info
示例10: validate_converted_data
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def validate_converted_data(data):
error = None
if error is None and not data.get("deviceName"):
error = 'deviceName is empty in data: '
if error is None and not data.get("deviceType"):
error = 'deviceType is empty in data: '
if error is None and not data.get("attributes") and not data.get("telemetry"):
error = 'No telemetry and attributes in data: '
if error is not None:
json_data = dumps(data)
if isinstance(json_data, bytes):
log.error(error+json_data.decode("UTF-8"))
else:
log.error(error + json_data)
return False
return True
示例11: createVizFromTable
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def createVizFromTable(self, table, name, description='', returnDict=True):
self.returnDict = returnDict
payload = {
'type': 'derived',
'name': name,
'title': name,
'description': description,
'tags': ['QGISCartoDB'],
"tables": [table]
}
url = QUrl(self.apiUrl + "viz/?api_key={}".format(self.apiKey))
request = self._getRequest(url)
reply = self.manager.post(request, json.dumps(payload))
loop = QEventLoop()
reply.downloadProgress.connect(self.progressCB)
reply.error.connect(self._error)
reply.finished.connect(loop.exit)
loop.exec_()
示例12: test_separators
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def test_separators(self):
lst = [1,2,3,4]
expect = '[\n1,\n2,\n3,\n4\n]'
expect_spaces = '[\n1, \n2, \n3, \n4\n]'
# Ensure that separators still works
self.assertEqual(
expect_spaces,
json.dumps(lst, indent=0, separators=(', ', ': ')))
# Force the new defaults
self.assertEqual(
expect,
json.dumps(lst, indent=0, separators=(',', ': ')))
# Added in 2.1.4
self.assertEqual(
expect,
json.dumps(lst, indent=0))
示例13: json
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
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)
示例14: feature_detail
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def feature_detail(request, id):
feature = get_object_or_404(Feature, pk=id)
geojson = json.dumps(feature.get_geojson())
d = RequestContext(request, {
'feature': feature,
'geojson': geojson
})
return render_to_response("feature.html", d)
示例15: navchartdatajson
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import dumps [as 別名]
def navchartdatajson():
data = generatenav(current_user.username)
# Generate data for NAV chart
navchart = data[["NAV_fx"]]
# dates need to be in Epoch time for Highcharts
navchart.index = (navchart.index - datetime(1970, 1, 1)).total_seconds()
navchart.index = navchart.index * 1000
navchart.index = navchart.index.astype(np.int64)
navchart = navchart.to_dict()
navchart = navchart["NAV_fx"]
navchart = json.dumps(navchart)
return navchart