gpt4 book ai didi

python - 如何确定我对 API 的 Python 请求调用是否未返回任何数据

转载 作者:太空狗 更新时间:2023-10-29 20:12:13 24 4
gpt4 key购买 nike

我有一个使用 Python 请求的求职板 API 查询。然后它写入包含在网页中的表格。有时请求不会返回任何数据(如果没有空缺职位)。如果是这样,我想将一个字符串写入包含的文件而不是表格。识别无数据响应的最佳方法是什么?它是否简单如:if response = "", 或类似的东西?这是我发出 API 请求的 Python 代码:

#!/usr/bin/python
import requests
import json
from datetime import datetime
import dateutil.parser
url = "https://data.usajobs.gov/api/Search"

querystring = {"Organization":"LF00","WhoMayApply":"All"}

headers = {
'authorization-key': "ZQbNd1iLrQ+rPN3Rj2Q9gDy2Qpi/3haXSXGuHbP1SRk=",
'user-agent': "jcarroll@fec.gov",
'host': "data.usajobs.gov",
'cache-control': "no-cache",
}

response = requests.request("GET", url, headers=headers, params=querystring)


responses=response.json()



with open('/Users/jcarroll/work/infoweb_branch4/rep_infoweb/trunk/fec_jobs.html', 'w') as jobtable:

jobtable.write("Content-Type: text/html\n\n")
table_head="""<table class="job_table" style="border:#000">
<tbody>
<tr>
<th>Vacancy</th>
<th>Grade</th>
<th>Open Period</th>
<th>Who May Apply</th>
</tr>"""
jobtable.write(table_head)
for i in responses['SearchResult']['SearchResultItems']:
start_date = dateutil.parser.parse(i['MatchedObjectDescriptor']['PositionStartDate'])
end_date = dateutil.parser.parse(i['MatchedObjectDescriptor']['PositionEndDate'])
jobtable.write("<tr><td><strong><a href='" + i['MatchedObjectDescriptor']['PositionURI'] + "'>" + i['MatchedObjectDescriptor']['PositionID'] + ", " + i['MatchedObjectDescriptor']['PositionTitle'] + "</a></strong></td><td>" + i['MatchedObjectDescriptor']['JobGrade'][0]['Code'] + "-" + i['MatchedObjectDescriptor']['UserArea']['Details']['LowGrade']+ " - " + i['MatchedObjectDescriptor']['UserArea']['Details']['HighGrade'] + "</td><td>" + start_date.strftime('%b %d, %Y')+ " - " + end_date.strftime('%b %d, %Y')+ "</td><td>" + i['MatchedObjectDescriptor']['UserArea']['Details']['WhoMayApply']['Name'] + "</td></tr>")

jobtable.write("</tbody></table>")

jobtable.close

最佳答案

根据响应的实际情况,您有几个选项。我假设情况 3 最适用:

# 1. Test if response body contains sth.
if response.text: # body as str
# ...
# body = response.content: # body as bytes, useful for binary data

# 2. Handle error if deserialization fails (because of no text or bad format)
try:
json_data = response.json()
# ...
except ValueError:
# no JSON returned

# 3. check that .json() did NOT return an empty dict/list
if json_data:
# ...

# 4. safeguard against malformed/unexpected data structure
try:
data_point = json_data[some_key][some_index][...][...]
except (KeyError, IndexError, TypeError):
# data does not have the inner structure you expect

# 5. check if data_point is actually something useful (truthy in this example)
if data_point:
# ...
else:
# data_point is falsy ([], {}, None, 0, '', ...)

关于python - 如何确定我对 API 的 Python 请求调用是否未返回任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37605278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com