AttributeError:“ str”对象没有属性“ status_code”

时间:2018-12-03 08:26:03

标签: python api flask http-status-codes

我遇到以下错误

AttributeError: 'str' object has no attribute 'status_code'

我正在通过API获取数据,当API关闭时,该值为“关闭”

@app.route('/test_api')
def test_api():
    ipno = "192.168.0.120"
    port = "8060"

    url_time = 'https://{}:{}/time/'.format(ipno, port)
    url_member = 'https://{}:{}/member/'.format(ipno, port)
    url_state = 'https://{}:{}/state/'.format(ipno, port)

    if url_time.status_code == requests.codes.ok:

        r_time = _session.get(url_time).content
    else:
        r_time = "Time is down"

    if url_member.status_code == requests.codes.ok:

        r_member = _session.get(url_member).content
    else:
        r_member = "Member is down"

    if url_state.status_code == requests.codes.ok:

        r_state = _session.get(url_state).content
    else:
        r_state = "State is down"


    return render_template('test_api.html', time = json.loads(r_time), member=json.loads(r_member), state=json.loads(r_state))

2 个答案:

答案 0 :(得分:1)

您没有使用请求库发出实际请求:

url_time = 'https://{}:{}/time/'.format(ipno, port)
time_request = requests.get(url_time)
if time_request.status_code == requests.codes.ok:
    r_time = _session.get(url_time).content

答案 1 :(得分:0)

if url_time.status_code == requests.codes.ok:行中:

url_time是一个字符串,这就是您收到错误的原因。字符串不具有属性status_code