【问题标题】:Checking the validation of a JSON response with Python使用 Python 检查 JSON 响应的验证
【发布时间】:2021-11-19 11:48:20
【问题描述】:

我想检查这些端点,如果答案不是 0 则可以,但如果答案为 0 则不行。 完成这些检查后,我想将结果发送到“outlook”电子邮件,任何人都可以帮助我。

这是我目前的代码。

import json, requests, urllib.parse, re
from termcolor import colored
import numpy as np

cdwenv1 = 'cdwu' #Note that it only works with the http version right now
cdwenv2 = 'cdwp'

#Dev Static
cdwenv  = '' #leave empty

# static
cdwEndPoints = [
                 'http://cdwu/cdw/counterparties?count=true'
                ,'http://cdwu/identifier/assets?count=true'
                ,'http://cdwu/identifier/assetListings?count=true'
]

# Check that Counts are different from 0
import sys

def countsCDWdata(input: list, cdwenv1, flag=0):
   results = []
   for i, item in enumerate(input):
        result = []
        if '?' in item:
            cdwcounturl = item
        try:
            r = requests.get(cdwcounturl)
        except:
                print(cdwcounturl, colored('is erroring', 'red'))
        result.append([cdwenv1, r.text])
        sys.stdout.flush()
        sys.stdout.write('\r Queried '+ str(i) + ' out of ' + str(len(input)))   
        results.append([re.findall('//.*?/.*?/(.*?)/',item)[0], result[0], result[0]])
   if flag == 1:
      return(results)
   df = pd.DataFrame(results, columns = ['CDWEndpoint', 'CDW Env', 'Counts'])
   df['Status'] = np.where(df['Counts1'] != 0, colored('Ok', 'green'), colored('not Ok', 'red'))
   sys.stdout.flush()
   sys.stdout.write('\r')
   print(df)

我收到此错误:

http://cdwu/cdw/counterparties?count=true is erroring
---------------------------------------------------------------------------
http://cdwu/cdw/counterparties?count=true is erroring
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-72-797620017bbc> in <module>()
----> 1 countsCDWdata(cdwEndPoints, [cdwenv1])

<ipython-input-70-73176a33caf9> in countsCDWdata(input, cdwenv1, flag)
      9         except:
     10                 print(cdwcounturl, colored('is erroring', 'red'))
---> 11         result.append([cdwenv1, r.text])
     12         sys.stdout.flush()
     13         sys.stdout.write('\r Queried '+ str(i) + ' out of ' + str(len(input)))

UnboundLocalError: local variable 'r' referenced before assignment

【问题讨论】:

  • r 变量仅分配到第 12 行 => 你没有实现尝试,属于例外 => r 类型的“不存在”。这导致了这个错误。并查看错误http://cdwu/cdw/counterparties?count=true is erroring的第一行,它看起来像错误打印第14行。
  • 尽管有前面的评论,使用 input 作为变量名是不可取的

标签: python json python-3.x api automation


【解决方案1】:
import json
import jsonschema
from jsonschema import validate

def validateJson(jsonData):
    try:
        validate(instance=jsonData, schema=studentSchema)
    except jsonschema.exceptions.ValidationError as err:
        return False
    return True

【讨论】:

  • 请找到official docs,其中解释了jsonschema.validate。可能需要在此级别不捕获异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多