猿问

使用flask python issue获取响应status_code

我想使用 Flask python 获得监控服务的响应 HTTP status_code。


我的代码:


from flask import Flask, request, url_for, redirect, render_template, flash, Response, abort


import requests


res = requests.get('https://192.168.1.100:8000/token?api=API',verify=False)

app = Flask(__name__)

print(res.url) # your.domain/test/3/3


print(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  

但我的代码没有正常工作。


我的预期结果,它将由单独的 HTTP 状态代码返回:201 或 401 或 500,无论我在if条件中定义什么。


任何帮助表示赞赏!!!


白板的微信
浏览 371回答 1
1回答

翻阅古今

状态代码是int,不是str。因此,请检查201,而不是'201'。你的代码应该是:if request.method == "GET" or request.method == "POST":&nbsp;&nbsp; &nbsp; if res.status_code == 201:&nbsp; &nbsp; &nbsp; &nbsp; # do what you want here详情请见下文。>>> import requests>>> r = requests.get('https://httpbin.org/get')>>> r.status_code200>>> type(r.status_code)<class 'int'>
随时随地看视频慕课网APP

相关分类

Python
我要回答