如何确定我的 Python 请求 API 调用是否不返回数据

问题描述 投票:0回答:2

我使用 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': "XXXXX",
    'user-agent': "XXX@XXX",
    '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
python json
2个回答
54
投票

根据实际的反应,您有几个选择。我认为情况 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, '', ...)

2
投票

如果您的 API 已使用正确的状态代码编写,则

  1. 200表示身体反应成功
  2. 204 表示无正文响应成功。

在Python中你可以像下面这样简单地检查你的需求

if 204 == response.status_code :
    # do something awesome
© www.soinside.com 2019 - 2024. All rights reserved.