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

前端 未结 1 629
北恋
北恋 2021-01-31 20:04

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 op

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 20:24

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

    0 讨论(0)
提交回复
热议问题