我想使用 Flask python 獲得監(jiān)控服務(wù)的響應(yīng) HTTP status_code。我的代碼:from flask import Flask, request, url_for, redirect, render_template, flash, Response, abortimport requestsres = requests.get('https://192.168.1.100:8000/token?api=API',verify=False)app = Flask(__name__)print(res.url) # your.domain/test/3/3print(res.status_code) # 200@app.route('/services')def check_services(): if request.method == "GET" or request.method == "POST": if res.status_code == '201': result = 'Sucess HTTP.Status_code 201 - Service TOKEN is working fine [OK]' return render_template('services.html'), 201# result = '401 -- Service TOKEN is working fine - parameter is not correct' else:# abort(401) return render_template('services401.html'),401 但我的代碼沒有正常工作。我的預(yù)期結(jié)果,它將由單獨(dú)的 HTTP 狀態(tài)代碼返回:201 或 401 或 500,無(wú)論我在if條件中定義什么。任何幫助表示贊賞?。?!
1 回答

翻閱古今
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
狀態(tài)代碼是int,不是str。因此,請(qǐng)檢查201,而不是'201'。你的代碼應(yīng)該是:
if request.method == "GET" or request.method == "POST":
if res.status_code == 201:
# do what you want here
詳情請(qǐng)見下文。
>>> import requests
>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200
>>> type(r.status_code)
<class 'int'>
添加回答
舉報(bào)
0/150
提交
取消