当前位置: 首页>>代码示例>>Python>>正文


Python simplejson.dumps方法代码示例

本文整理汇总了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 
开发者ID:pxsocs,项目名称:thewarden,代码行数:26,代码来源:routes.py

示例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
# ------------------------------------ 
开发者ID:pxsocs,项目名称:thewarden,代码行数:21,代码来源:routes.py

示例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 
开发者ID:Yelp,项目名称:threat_intel,代码行数:20,代码来源:api_cache_test.py

示例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 
开发者ID:fangpenlin,项目名称:bugbuzz-python,代码行数:23,代码来源:__init__.py

示例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))) 
开发者ID:flipkart-incubator,项目名称:watchdog,代码行数:22,代码来源:wappalyzer.py

示例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) 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:23,代码来源:custom_mqtt_uplink_converter.py

示例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) 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:20,代码来源:tb_gateway_service.py

示例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) 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:21,代码来源:tb_gateway_remote_configurator.py

示例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 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:19,代码来源:tb_gateway_mqtt.py

示例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 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:18,代码来源:tb_utility.py

示例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_() 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:21,代码来源:cartodbapi.py

示例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)) 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:18,代码来源:test_indent.py

示例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) 
开发者ID:NatanaelAntonioli,项目名称:L.E.S.M.A,代码行数:12,代码来源:L.E.S.M.A. - Fabrica de Noobs Speedtest.py

示例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) 
开发者ID:LibraryOfCongress,项目名称:gazetteer,代码行数:10,代码来源:views.py

示例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 
开发者ID:pxsocs,项目名称:thewarden,代码行数:14,代码来源:routes.py


注:本文中的simplejson.dumps方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。