當前位置: 首頁>>代碼示例>>Python>>正文


Python json.JSONDecodeError方法代碼示例

本文整理匯總了Python中json.JSONDecodeError方法的典型用法代碼示例。如果您正苦於以下問題:Python json.JSONDecodeError方法的具體用法?Python json.JSONDecodeError怎麽用?Python json.JSONDecodeError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在json的用法示例。


在下文中一共展示了json.JSONDecodeError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: req_json

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def req_json(self, req):
        if req.content_length is None or req.content_length == 0:
            return None

        if req.content_type is not None and req.content_type.lower(
        ) == 'application/json':
            raw_body = req.stream.read(req.content_length or 0)

            if raw_body is None:
                return None

            try:
                json_body = json.loads(raw_body.decode('utf-8'))
                return json_body
            except json.JSONDecodeError as jex:
                print(
                    "Invalid JSON in request: \n%s" % raw_body.decode('utf-8'))
                self.error(
                    req.context,
                    "Invalid JSON in request: \n%s" % raw_body.decode('utf-8'))
                raise errors.InvalidFormat(
                    "%s: Invalid JSON in body: %s" % (req.path, jex))
        else:
            raise errors.InvalidFormat("Requires application/json payload") 
開發者ID:airshipit,項目名稱:drydock,代碼行數:26,代碼來源:base.py

示例2: get

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def get(self, url, require_json=False, **kwargs):
        """
        :param require_json: If require_json is True and
        the result is not json-encoded, will raise error
        then have a retry.
        :rtype: requests.Response
        """
        if 'timeout' in kwargs:
            kwargs.pop('timeout')
        resp = self.session.get(url, timeout=(2, 30), **kwargs)
        if require_json:
            try:
                resp.json()
            except JSONDecodeError:
                download_logger.error(
                    "Failed to convert resp to json for url {}: {}".format(
                        url,
                        resp.text,
                    )
                )
                raise
        return resp 
開發者ID:winkidney,項目名稱:PickTrue,代碼行數:24,代碼來源:huaban.py

示例3: handle_raw_data

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def handle_raw_data(self, retrieve_io_data):
        try:
            io_data = retrieve_io_data()
            if io_data is None or io_data.is_empty():
                return

            data_as_dict = json.loads(io_data.get_data())
            handled = self.handle_message(data_as_dict, io_data)

            if not handled:
                logging.info(
                    "Protocol message was not handled because "
                    "no handler was registered.",
                )

        except json.JSONDecodeError:
            logging.info(
                "Protocol message was ignored because it was not valid JSON.",
            )

        except:
            logging.exception("Exception when handling protocol message:")
            raise 
開發者ID:typeintandem,項目名稱:tandem,代碼行數:25,代碼來源:base.py

示例4: read_client_auth_request

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def read_client_auth_request(request: web.Request) -> Tuple[Optional[AuthRequestInfo],
                                                                  Optional[web.Response]]:
    server_name = request.match_info.get("server", None)
    server = registration_secrets().get(server_name, None)
    if not server:
        return None, resp.server_not_found
    try:
        body = await request.json()
    except JSONDecodeError:
        return None, resp.body_not_json
    try:
        username = body["username"]
        password = body["password"]
    except KeyError:
        return None, resp.username_or_password_missing
    try:
        base_url = server["url"]
        secret = server["secret"]
    except KeyError:
        return None, resp.invalid_server
    api = HTTPAPI(base_url, "", loop=get_loop())
    user_type = body.get("user_type", "bot")
    return AuthRequestInfo(api, secret, username, password, user_type), None 
開發者ID:maubot,項目名稱:maubot,代碼行數:25,代碼來源:client_auth.py

示例5: login

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def login(request: web.Request) -> web.Response:
    try:
        data = await request.json()
    except json.JSONDecodeError:
        return resp.body_not_json
    secret = data.get("secret")
    if secret and get_config()["server.unshared_secret"] == secret:
        user = data.get("user") or "root"
        return resp.logged_in(create_token(user))

    username = data.get("username")
    password = data.get("password")
    if get_config().check_password(username, password):
        return resp.logged_in(create_token(username))

    return resp.bad_auth 
開發者ID:maubot,項目名稱:maubot,代碼行數:18,代碼來源:login.py

示例6: login

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def login(server, username, password, alias) -> None:
    data = {
        "username": username,
        "password": password,
    }
    try:
        with urlopen(f"{server}/_matrix/maubot/v1/auth/login",
                     data=json.dumps(data).encode("utf-8")) as resp_data:
            resp = json.load(resp_data)
            config["servers"][server] = resp["token"]
            if not config["default_server"]:
                print(Fore.CYAN, "Setting", server, "as the default server")
                config["default_server"] = server
            if alias:
                config["aliases"][alias] = server
            save_config()
            print(Fore.GREEN + "Logged in successfully")
    except HTTPError as e:
        try:
            err = json.load(e)
        except json.JSONDecodeError:
            err = {}
        print(Fore.RED + err.get("error", str(e)) + Fore.RESET) 
開發者ID:maubot,項目名稱:maubot,代碼行數:25,代碼來源:login.py

示例7: update_manager_status

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def update_manager_status(request: web.Request, params: Any) -> web.Response:
    log.info('MANAGER.UPDATE_MANAGER_STATUS (status:{}, force_kill:{})',
             params['status'], params['force_kill'])
    try:
        params = await request.json()
        status = params['status']
        force_kill = params['force_kill']
    except json.JSONDecodeError:
        raise InvalidAPIParameters(extra_msg='No request body!')
    except (AssertionError, ValueError) as e:
        raise InvalidAPIParameters(extra_msg=str(e.args[0]))

    if force_kill:
        await request.app['registry'].kill_all_sessions()
    await request.app['config_server'].update_manager_status(status)

    return web.Response(status=204) 
開發者ID:lablup,項目名稱:backend.ai-manager,代碼行數:19,代碼來源:manager.py

示例8: Pip6UserAgent

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def Pip6UserAgent(user_agent):
    # We're only concerned about pip user agents.
    if not user_agent.startswith("pip/"):
        raise UnableToParse

    # This format was brand new in pip 6.0, so we'll need to restrict it
    # to only versions of pip newer than that.
    version_str = user_agent.split()[0].split("/", 1)[1]
    version = packaging.version.parse(version_str)
    if version not in SpecifierSet(">=6", prereleases=True):
        raise UnableToParse

    try:
        return json.loads(user_agent.split(maxsplit=1)[1])
    except (json.JSONDecodeError, UnicodeDecodeError, IndexError):
        raise UnableToParse from None 
開發者ID:pypa,項目名稱:linehaul,代碼行數:18,代碼來源:parser.py

示例9: get_alerts_by_key_value

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def get_alerts_by_key_value(self, key, value):
        self.update_access_token()
        self.update_time_from()

        full_endpoint_url = self.setup_alerts_endpoint()
        self.logger.info("Connecting to: " + full_endpoint_url)

        response = self.session.get(full_endpoint_url)
        self.raise_exception_on_error(response)

        matching_alerts = []

        self.logger.info("Looking for {} matching {}".format(value, key))

        try:
            matching_alerts = list(filter(lambda a: a.get(key) == value, response.json()))
        except json.JSONDecodeError as e:
            self.logger.error("Alerts returned were in an unexpected format!")
            raise e

        return komand.helper.clean(matching_alerts) 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:23,代碼來源:connection.py

示例10: parse

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def parse(text: str, path: Path, rev: str) -> List[RepoEntry]:
        try:
            fromtext = json.loads(text)
        except json.JSONDecodeError as e:
            print("Failed to parse json in {}:{}: {}".format(path, rev, e.msg))
            sys.exit(1)

        entries = []
        fmt = Format.from_path(path)
        if fmt is Format.Manifest:
            for entry in fromtext:
                entries.append(OriginalEntry.from_dict(entry))
        if fmt is Format.Lock:
            for _, entry in fromtext.items():
                entries.append(OriginalEntry.from_dict(entry))

        # Check for duplicates
        names = [entry.checkout_path for entry in entries]
        if len(names) != len(set(names)):
            dup = set([x for x in names if names.count(x) > 1])
            print("Two repositories have same checkout path in {}:{}: {}".format(path, rev, dup))
            sys.exit(1)

        return entries 
開發者ID:sifive,項目名稱:wit,代碼行數:26,代碼來源:repo_entries.py

示例11: build_status_header

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def build_status_header(self):
        """Build org-admin header for internal status delivery."""
        try:
            encoded_auth_header = self._identity_header.get("x-rh-identity")
            identity = json.loads(b64decode(encoded_auth_header))
            account = identity["identity"]["account_number"]

            identity_header = {
                "identity": {
                    "account_number": account,
                    "type": "User",
                    "user": {"username": "cost-mgmt", "email": "cost-mgmt@redhat.com", "is_org_admin": True},
                }
            }
            json_identity = json_dumps(identity_header)
            cost_internal_header = b64encode(json_identity.encode("utf-8"))

            return {"x-rh-identity": cost_internal_header}
        except (binascii.Error, json.JSONDecodeError, TypeError, KeyError) as error:
            LOG.error(f"Unable to build internal status header. Error: {str(error)}") 
開發者ID:project-koku,項目名稱:koku,代碼行數:22,代碼來源:sources_http_client.py

示例12: test_request_sources_error

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def test_request_sources_error(status_code, error, error_body, caplog):
    responses.add(
        responses.POST,
        '{}/api/v1/requests'.format(CACHITO_URL),
        content_type='application/json',
        body=error_body,
        status=status_code,
    )

    with pytest.raises(error):
        CachitoAPI(CACHITO_URL).request_sources(CACHITO_REQUEST_REPO, CACHITO_REQUEST_REF)

    try:
        response_data = json.loads(error_body)
    except ValueError:  # json.JSONDecodeError in py3
        assert 'Cachito response' not in caplog.text
    else:
        response_json = 'Cachito response:\n{}'.format(json.dumps(response_data, indent=4))
        # Since Python 3.7 logger adds additional whitespaces by default -> checking without them
        assert re.sub(r'\s+', " ", response_json) in re.sub(r'\s+', " ", caplog.text) 
開發者ID:containerbuildsystem,項目名稱:atomic-reactor,代碼行數:22,代碼來源:test_cachito.py

示例13: _onMessage

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def _onMessage(self, msg):
        try:
            data = json.loads(msg)
        except json.JSONDecodeError:
            # Something wrong with this data, log and discard
            return
        if isinstance(data, dict):
            if 'topics' in data:
                self._response_handler(data['topics'])
            elif 'type' in data:
                type = data.pop('type')
                self._data_handler(type, data)


        else:
            pass 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:18,代碼來源:fcoin_client.py

示例14: clean_result

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def clean_result(resp):
        if resp.status_code >= 500:
            msg = "Response code is {0.status_code}: {0.text}".format(resp)
            logger.error(msg)
            raise ResponseError(msg)

        try:
            _ = resp.json()
        except (json.JSONDecodeError, simplejson.scanner.JSONDecodeError):
            msg = "Response json couldn't be decode: {0.text}".format(resp)
            logger.error(msg)
            raise ResponseError(msg)
        else:
            return resp 
開發者ID:jumpserver,項目名稱:jumpserver-python-sdk,代碼行數:16,代碼來源:request.py

示例15: test_clean_result_decode_error

# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecodeError [as 別名]
def test_clean_result_decode_error(self):
        resp_mock = mock.MagicMock()
        resp_mock.status_code = 200
        resp_mock.json.side_effect = json.JSONDecodeError("error", "\n\n", 1)

        with self.assertRaises(ResponseError):
            self.http.clean_result(resp_mock) 
開發者ID:jumpserver,項目名稱:jumpserver-python-sdk,代碼行數:9,代碼來源:test_request.py


注:本文中的json.JSONDecodeError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。