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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37605278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:38:39  来源:igfitidea点击:

How to determine if my Python Requests call to API returns no data

pythonjson

提问by JohnnyP

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:

我使用 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': "[email protected]",
    '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

回答by schwobaseggl

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

您有几个选项,具体取决于响应的实际内容。我认为,情况 3 最适用:

# 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, '', ...)