【问题标题】:Get response status_code using flask python issue使用烧瓶 python 问题获取响应 status_code
【发布时间】:2019-07-16 05:25:36
【问题描述】:

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

我的代码:

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 条件中定义什么。

任何帮助表示赞赏!!!

【问题讨论】:

    标签: python api flask


    【解决方案1】:

    状态码是int,而不是str。因此,请使用201,而不是'201'。 你的代码应该是:

    if request.method == "GET" or request.method == "POST": 
        if res.status_code == 201:
            # do what you want here
    

    详情见下文。

    >>> import requests
    >>> r = requests.get('https://httpbin.org/get')
    >>> r.status_code
    200
    >>> type(r.status_code)
    <class 'int'>
    

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2017-12-04
      相关资源
      最近更新 更多