python调用外部api返回数据,如何确定我的Python请求对API的调用是否不返回数据

I have a query to an job board API using Python Requests. It then writes to a table, that is included in a web page. Sometimes the request will return no data(if there are no open jobs). If so, I want to write a string to the included file instead of the table. What is the best way to identify a response of no data? Is it as simple as: if response = "", or something along those lines?

Here is my Python code making the API request:

#!/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="""

VacancyGradeOpen PeriodWho May Apply

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("

" + i['MatchedObjectDescriptor']['PositionID'] + ", " + i['MatchedObjectDescriptor']['PositionTitle'] + "" + i['MatchedObjectDescriptor']['JobGrade'][0]['Code'] + "-" + i['MatchedObjectDescriptor']['UserArea']['Details']['LowGrade']+ " - " + i['MatchedObjectDescriptor']['UserArea']['Details']['HighGrade'] + "" + start_date.strftime('%b %d, %Y')+ " - " + end_date.strftime('%b %d, %Y')+ "" + i['MatchedObjectDescriptor']['UserArea']['Details']['WhoMayApply']['Name'] + "")

jobtable.write("

")

jobtable.close

解决方案

You have a couple of options depending on what the response actually is. I assume, case 3 applies best:

# 1. Test if response body contains sth.

if response.text:

# ...

# 2. Handle error if deserialization fails (because of no text or bad format)

try:

responses = response.json()

# ...

except ValueError:

# no JSON returned

# 3. check that .json() did NOT return an empty dict

if responses:

# ...

# 4. safeguard against malformed data

try:

data = responses[some_key][some_index][...][...]

except (IndexError, KeyError, TypeError):

# data does not have the inner structure you expect

# 5. check if data is actually something useful (truthy in this example)

if data:

# ...

else:

# data is falsy ([], {}, None, 0, '', ...)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值