How to use the simplejson.JSONDecodeError function in simplejson

To help you get started, we’ve selected a few simplejson examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github getsentry / sentry / src / test_only_plugins / github / endpoints / webhook.py View on Github external
method, signature = request.META["HTTP_X_HUB_SIGNATURE"].split("=", 1)
        except (KeyError, IndexError):
            logger.error(
                "github.webhook.missing-signature", extra=self.get_logging_data(organization)
            )
            return HttpResponse(status=400)

        if not self.is_valid_signature(method, body, self.get_secret(organization), signature):
            logger.error(
                "github.webhook.invalid-signature", extra=self.get_logging_data(organization)
            )
            return HttpResponse(status=401)

        try:
            event = json.loads(body.decode("utf-8"))
        except JSONDecodeError:
            logger.error(
                "github.webhook.invalid-json",
                extra=self.get_logging_data(organization),
                exc_info=True,
            )
            return HttpResponse(status=400)

        handler()(event, organization=organization)
        return HttpResponse(status=204)
github aneisch / home-assistant-config / custom_components / alexa_media / alarm_control_panel.py View on Github external
async def init(self):
        try:
            from simplejson import JSONDecodeError
            data = await self.alexa_api.get_guard_details(self._login)
            guard_dict = (data['locationDetails']
                          ['locationDetails']['Default_Location']
                          ['amazonBridgeDetails']['amazonBridgeDetails']
                          ['LambdaBridge_AAA/OnGuardSmartHomeBridgeService']
                          ['applianceDetails']['applianceDetails'])
        except (KeyError, TypeError, JSONDecodeError):
            guard_dict = {}
        for key, value in guard_dict.items():
            if value['modelName'] == "REDROCK_GUARD_PANEL":
                self._appliance_id = value['applianceId']
                self._guard_entity_id = value['entityId']
                self._friendly_name += " " + self._appliance_id[-5:]
                _LOGGER.debug("%s: Discovered %s: %s %s",
                              self.account,
                              self._friendly_name,
                              self._appliance_id,
                              self._guard_entity_id)
        if not self._appliance_id:
            _LOGGER.debug("%s: No Alexa Guard entity found", self.account)
github PokeAPI / pokepy / pykemon / request.py View on Github external
def _to_json(data):
    try:
        content = simplejson.loads(data)
        return content
    except JSONDecodeError:
        raise JSONDecodeError('Error decoding data', data, 0)
github torn8o / Home-AssistantConfig / custom_components / media_player / alexa.py View on Github external
self._session.cookies = cookies

        get_resp = self._session.get('https://alexa.' + self._url +
                                     '/api/devices-v2/device')
        # with open(self._debugget, mode='wb') as localfile:
        #     localfile.write(get_resp.content)

        try:
            from json.decoder import JSONDecodeError
            from simplejson import JSONDecodeError as SimpleJSONDecodeError
            # Need to catch both as Python 3.5 appears to use simplejson
        except ImportError:
            JSONDecodeError = ValueError
        try:
            get_resp.json()
        except (JSONDecodeError, SimpleJSONDecodeError) as ex:
            # ValueError is necessary for Python 3.5 for some reason
            template = ("An exception of type {0} occurred."
                        " Arguments:\n{1!r}")
            message = template.format(type(ex).__name__, ex.args)
            _LOGGER.debug("Not logged in: {}".format(message))
            return False
        _LOGGER.debug("Logged in.")
        return True
github mozilla / build-tools / lib / python / kickoff / buglist_creator.py View on Github external
def create_short_url_with_prefix(buglist, backout_buglist):
    # Create link if there are bugs, else empty string
    urls = []
    for set_of_bugs, prefix in [(buglist, BUGLIST_PREFIX), (backout_buglist, BACKOUT_PREFIX)]:
        if set_of_bugs and len(set_of_bugs) < MAX_BUGS_IN_BUGLIST:
            try:
                long_bugzilla_link = BUGZILLA_BUGLIST_TEMPLATE.format(bugs='%2C'.join(set_of_bugs))
                url = requests.get(URL_SHORTENER_TEMPLATE.format(url=long_bugzilla_link)).json()['url']
                url = prefix + url + '\n'

            except (KeyError, JSONDecodeError,):
                # If the Bugzilla link fails despite limiting the number of bugs, don't make the url and continue
                url = ''
        else:
            url = ''

        urls.append(url)

    return urls[0], urls[1]
github apache / incubator-superset / superset / views / core.py View on Github external
def sql_json_exec(
        self, query_params: dict, log_params: Optional[Dict[str, Any]] = None
    ):
        """Runs arbitrary sql and returns data as json"""
        # Collect Values
        database_id: int = cast(int, query_params.get("database_id"))
        schema: str = cast(str, query_params.get("schema"))
        sql: str = cast(str, query_params.get("sql"))
        try:
            template_params: dict = json.loads(
                query_params.get("templateParams") or "{}"
            )
        except json.JSONDecodeError:
            logging.warning(
                f"Invalid template parameter {query_params.get('templateParams')}"
                " specified. Defaulting to empty dict"
            )
            template_params = {}
        limit: int = query_params.get("queryLimit") or app.config["SQL_MAX_ROW"]
        async_flag: bool = cast(bool, query_params.get("runAsync"))
        if limit < 0:
            logging.warning(
                f"Invalid limit of {limit} specified. Defaulting to max limit."
            )
            limit = 0
        select_as_cta: bool = cast(bool, query_params.get("select_as_cta"))
        tmp_table_name: str = cast(str, query_params.get("tmp_table_name"))
        client_id: str = cast(
            str, query_params.get("client_id") or utils.shortid()[:10]
github getsentry / sentry / src / sentry / integrations / github_enterprise / webhook.py View on Github external
if not body:
            logger.warning("github_enterprise.webhook.missing-body", extra=self.get_logging_data())
            return HttpResponse(status=400)

        try:
            handler = self.get_handler(request.META["HTTP_X_GITHUB_EVENT"])
        except KeyError:
            logger.warning("github_enterprise.webhook.missing-event", extra=self.get_logging_data())
            return HttpResponse(status=400)

        if not handler:
            return HttpResponse(status=204)

        try:
            event = json.loads(body.decode("utf-8"))
        except JSONDecodeError:
            logger.warning(
                "github_enterprise.webhook.invalid-json",
                extra=self.get_logging_data(),
                exc_info=True,
            )
            return HttpResponse(status=400)

        try:
            host = request.META["HTTP_X_GITHUB_ENTERPRISE_HOST"]
        except KeyError:
            logger.warning("github_enterprise.webhook.missing-enterprise-host")
            return HttpResponse(status=400)

        secret = self.get_secret(event, host)
        if not secret:
            logger.warning("github_enterprise.webhook.missing-integration", extra={"host": host})
github asdine / madame / madame / handler / collections.py View on Github external
"""

        if not self.app.config['COLLECTION_POST']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED", "Accepted media type : application/json")
        data = request.data
        if not data:
            return send_error(400, "EMPTY_DATA")
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        if isinstance(data, dict):
            status = self.validate(data, collection)
            if status['created']:
                base_url = request.base_url
                response = {'title': "Document created", 'links': []}
                response['links'].append(get_self_link(
                    title=self.app.DOMAINS[collection]['title'],
                    base_url=base_url,
                    description='You are here.',
                    methods=["GET", "POST", "DELETE"]
                ))
                response['links'].append(get_document_link(status['document'], base_url))
                return send_response(response, 201, get_etag(status['document']))
            else:
                return send_error(400, "VALIDATION_ERROR", status['issues'])
github DataDog / integrations-extras / sortdb / datadog_checks / sortdb / check.py View on Github external
tags=instance_tags,
                message="Request timeout: {}, {}".format(url, e),
            )
            self.timeout_event(url, timeout, aggregation_key)
            raise

        except (HTTPError, InvalidURL, ConnectionError) as e:
            self.service_check(
                self.SORTDB_SERVICE_CHECK,
                AgentCheck.CRITICAL,
                tags=instance_tags,
                message="Request failed: {0}, {1}".format(url, e),
            )
            raise

        except JSONDecodeError as e:
            self.service_check(
                self.SORTDB_SERVICE_CHECK,
                AgentCheck.CRITICAL,
                tags=instance_tags,
                message='JSON Parse failed: {0}, {1}'.format(url, e),
            )
            raise

        except ValueError as e:
            self.service_check(self.SORTDB_SERVICE_CHECK, AgentCheck.CRITICAL, tags=instance_tags, message=str(e))
            raise

        return response