本文整理汇总了Python中json.decoder.JSONDecodeError方法的典型用法代码示例。如果您正苦于以下问题:Python decoder.JSONDecodeError方法的具体用法?Python decoder.JSONDecodeError怎么用?Python decoder.JSONDecodeError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类json.decoder
的用法示例。
在下文中一共展示了decoder.JSONDecodeError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse_dag_json
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def _parse_dag_json(dag):
try:
dag = json.decode(dag)
except decoder.JSONDecodeError:
raise error.ValidationError('dag') from None
if not isinstance(dag, list):
raise error.ValidationError('dag')
new_dag = []
try:
for node in dag:
if any(k not in node for k in ['_id', 'require_nids', 'pids']):
raise error.ValidationError('dag')
new_node = {'_id': int(node['_id']),
'title': str(node.get('title', '')),
'require_nids': misc.dedupe(map(int, node['require_nids'])),
'pids': misc.dedupe(map(document.convert_doc_id, node['pids']))}
new_dag.append(new_node)
except ValueError:
raise error.ValidationError('dag') from None
return new_dag
示例2: fetch
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def fetch(self, year: int, month: int, sid: str, retry: int=5):
params = {'date': '%d%02d01' % (year, month), 'stockNo': sid}
for retry_i in range(retry):
r = requests.get(self.REPORT_URL, params=params,
proxies=get_proxies())
try:
data = r.json()
except JSONDecodeError:
continue
else:
break
else:
# Fail in all retries
data = {'stat': '', 'data': []}
if data['stat'] == 'OK':
data['data'] = self.purify(data)
else:
data['data'] = []
return data
示例3: _request
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def _request(self, method, path, params=None, payload=None,
forceNewToken=False, cleanJson=True):
self._set_token_header(forceNewToken)
url = self._get_complete_url(path)
response = requests.request(
method, url, params=params,
data=json.dumps(payload) if payload else payload,
headers=self._headers,
timeout=self.TIMEOUT)
if response.status_code == 200:
response.encoding = 'utf-8'
jsn = response.json()
if cleanJson and 'data' in jsn:
return jsn['data']
return jsn
elif not forceNewToken:
return self._request(method=method, path=path, params=params,
payload=payload, forceNewToken=True)
try:
raise Exception(response.json()['Error'])
except (JSONDecodeError, KeyError):
response.raise_for_status()
示例4: raw_autocomplete
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def raw_autocomplete(self, params, body=None):
url = settings["BRAGI_BASE_URL"] + "/autocomplete"
if body:
response = await self.client.post(url, params=params, json=body)
else:
response = await self.client.get(url, params=params)
if response.status_code != httpx.codes.ok:
try:
explain = response.json()["long"]
except (IndexError, JSONDecodeError):
explain = response.text
logger.error(
'Request to Bragi returned with unexpected status %d: "%s"',
response.status_code,
explain,
)
raise HTTPException(503, "Unexpected geocoder error")
try:
return response.json()
except (JSONDecodeError, pydantic.ValidationError) as e:
logger.exception("Autocomplete invalid response")
raise HTTPException(503, "Invalid response from the geocoder")
示例5: on_message
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def on_message(self, message):
logging.debug('{!r} from {}:{}'.format(message, *self.src_addr))
worker = self.worker_ref()
try:
msg = json.loads(message)
except JSONDecodeError:
return
if not isinstance(msg, dict):
return
resize = msg.get('resize')
if resize and len(resize) == 2:
try:
worker.chan.resize_pty(*resize)
except (TypeError, struct.error, paramiko.SSHException):
pass
data = msg.get('data')
if data and isinstance(data, UnicodeType):
worker.data_to_dst.append(data)
worker.on_write()
示例6: save_json
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def save_json(self, filename, data):
"""Atomically save a JSON file given a filename and a dictionary."""
path, ext = splitext(filename)
tmp_file = "{}.{}.tmp".format(path, randint(1000, 9999))
with open(tmp_file, 'w', encoding='utf-8') as f:
dump(data, f, indent=4,sort_keys=True,separators=(',',' : '))
try:
with open(tmp_file, 'r', encoding='utf-8') as f:
data = load(f)
except decoder.JSONDecodeError:
print("Attempted to write file {} but JSON "
"integrity check on tmp file has failed. "
"The original file is unaltered."
"".format(filename))
return False
except Exception as e:
print('A issue has occured saving ' + filename + '.\n'
'Traceback:\n'
'{0} {1}'.format(str(e), e.args))
return False
replace(tmp_file, filename)
return True
示例7: _split_options
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def _split_options(opts):
"""
Parse extra options (input or output) into a list
"""
if not opts:
return []
try:
if opts.startswith('['):
try:
ret = [str(s) for s in json.loads(opts)]
except JSONDecodeError as e:
ret = shlex.split(opts)
else:
ret = shlex.split(opts)
except Exception as e:
raise FFmpegNormalizeError(
"Could not parse extra_options: {}".format(e)
)
return ret
示例8: _send
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def _send(self, method: Method, endpoint: str, content: Union[bytes, str],
query_params: Dict[str, str], headers: Dict[str, str]) -> JSON:
while True:
request = self.session.request(str(method), endpoint, data=content,
params=query_params, headers=headers)
async with request as response:
if response.status < 200 or response.status >= 300:
errcode = message = None
try:
response_data = await response.json()
errcode = response_data["errcode"]
message = response_data["error"]
except (JSONDecodeError, ContentTypeError, KeyError):
pass
raise make_request_error(http_status=response.status,
text=await response.text(),
errcode=errcode, message=message)
if response.status == 429:
resp = await response.json()
await asyncio.sleep(resp["retry_after_ms"] / 1000, loop=self.loop)
else:
return await response.json()
示例9: get_reply
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def get_reply(cmd):
try:
j = json.loads(cmd, object_pairs_hook=OrderedDict)
if isinstance(j.get('error'), dict):
raise JSONRPCError(j['error'].get('code', 500),
j['error'].get('message'),
j['error'].get('data'))
elif 'result' not in j:
raise JSONRPCError(-32603, 'Internal error')
else:
return j['result']
except JSONDecodeError:
raise JSONRPCException
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
示例10: convert_result
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def convert_result(self, result):
if self.conversion_method == "none" or "result" not in result:
return result
try:
if self.conversion_method == "text":
result["result"] = str(result["result"])
elif self.conversion_method == "json":
result["result"] = loads(result["result"])
elif self.conversion_method == "xml":
result["result"] = parse(result["result"])
except (ExpatError, JSONDecodeError) as exc:
result = {
"success": False,
"text_response": result,
"error": f"Conversion to {self.conversion_method} failed",
"exception": str(exc),
}
return result
示例11: parse_error
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def parse_error(res: requests.Response) -> ApiError:
"""
Every server error should contain a "status" field with a human readable explanation of
what went wrong as well as a "error_type" field indicating the kind of error that can be mapped
to a Python type.
There's a fallback error UnknownError for other types of exceptions (network issues, api
gateway problems, etc.)
"""
try:
body = res.json()
except JSONDecodeError:
raise UnknownApiError(res.text)
if "error_type" not in body:
raise UnknownApiError(str(body))
error_type = body["error_type"]
status = body["status"]
if re.search(r"[0-9]+ qubits were requested, but the QVM is limited to [0-9]+ qubits.", status):
return TooManyQubitsError(status)
error_cls = error_mapping.get(error_type, UnknownApiError)
return error_cls(status)
示例12: validate_input
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def validate_input(handler):
async def _wrapper(wrapper: RequestWrapper):
try:
req_body = await wrapper.http_request.json()
except JSONDecodeError as e:
return json_response(
ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
status=HTTPStatus.BAD_REQUEST,
)
try:
job = ScheduledJob(**req_body)
except ValidationError as e:
return json_response(
ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
status=HTTPStatus.UNPROCESSABLE_ENTITY,
)
wrapper.types_registry.set(job)
return await call_http_handler(wrapper.http_request, handler)
return _wrapper
示例13: search_by_attribute_set
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def search_by_attribute_set(
url: str,
profile: FrozenSet[str],
limit: Optional[int] = 100,
namespace_filter: Optional[str]=None) -> Dict:
"""
Given a list of phenotypes, returns a ranked list of individuals
individuals can be filtered by namespace, eg MONDO, MGI, HGNC
:returns Dict with the structure: {
'unresolved' : [...]
'query_IRIs' : [...]
'results': {...}
}
:raises JSONDecodeError: If the response body does not contain valid json.
"""
owlsim_url = url + 'searchByAttributeSet'
params = {
'a': profile,
'limit': limit,
'target': namespace_filter
}
return requests.post(owlsim_url, data=params, timeout=TIMEOUT).json()
示例14: get_attribute_information_profile
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def get_attribute_information_profile(
url: str,
profile: Optional[FrozenSet[str]]=None,
categories: Optional[FrozenSet[str]]=None) -> Dict:
"""
Get the information content for a list of phenotypes
and the annotation sufficiency simple and
and categorical scores if categories are provied
Ref: https://zenodo.org/record/834091#.W8ZnCxhlCV4
Note that the simple score varies slightly from the pub in that
it uses max_max_ic instead of mean_max_ic
If no arguments are passed this function returns the
system (loaded cohort) stats
:raises JSONDecodeError: If the response body does not contain valid json.
"""
owlsim_url = url + 'getAttributeInformationProfile'
params = {
'a': profile,
'r': categories
}
return requests.post(owlsim_url, data=params, timeout=TIMEOUT).json()
示例15: search
# 需要导入模块: from json import decoder [as 别名]
# 或者: from json.decoder import JSONDecodeError [as 别名]
def search(
self,
id_list: List,
negated_classes: List,
limit: Optional[int] = 100,
method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResult:
"""
Owlsim2 search, calls search_by_attribute_set, and converts to SimResult object
:raises JSONDecodeError: If the owlsim response is not valid json.
"""
return self.filtered_search(
id_list=id_list,
negated_classes=negated_classes,
limit=limit,
taxon_filter=None,
category_filter=None,
method=method
)