【问题标题】:How to fix "NameError: global name 'ValidationError' is not defined"如何修复“NameError:未定义全局名称'ValidationError'”
【发布时间】:2019-08-27 00:24:13
【问题描述】:

我正在解决这个问题:

使用适当的 MongoDB 语句将新的键值对插入到文档中。具体来说,在 Python 或 Java 中创建函数或方法 这将从文件或标准输入流中读取 JSON 表示法的值对流,并将此文档插入到 stock 集合中。你 还需要创建一个简单的应用程序脚手架来测试您的函数或方法。

我已经开发了代码,它可以让我输入信息。但是总是会导致这个错误,不知道是什么原因造成的。

import json
from bson import json_util
from pymongo import MongoClient

connection = MongoClient('localhost', 27017)
db = connection['market']
collection = db['stocks']

def insert_document(document):
  checker = True
  try:
    stars = "*" * 50+"\n"
    print(stars)
    document = input('Enter Your Document: ')
    result = collection.insert_one(document)
    stars = "*" * 50+"\n"
    print ("\nSubmitted Document\n" + stars + document)

  except ValidationError as ve:
    abort(400, str(ve))
    checker = False
    stars = "*" * 50+"\n"
    return checker+stars

def main():
  myDocument = {"keyName": "test value data"}
  print insert_document(myDocument)
main()

预期结果:

*****************************************************
Enter Your Document: {"Ticker" : "123_EXAMPLE","Volume": 396,"Industry":"Example Industry Co."}
Submitted Document
*****************************************************
{"Ticker" : "123_EXAMPLE","Volume": 396,"Industry":"Example Industry Co."}
True
*****************************************************

实际结果:

**************************************************

Enter Your Document: {"Ticker" : "123_EXAMPLE","Volume": 396,"Industry":"Example Industry Co."}
Traceback (most recent call last):
  File "test.py", line 27, in <module>
    main()
  File "test.py", line 26, in main
    print insert_document(myDocument)
  File "test.py", line 19, in insert_document
    except ValidationError as ve:
NameError: global name 'ValidationError' is not defined

【问题讨论】:

    标签: mongodb input insert validationerror


    【解决方案1】:

    您的 ValidationError 消息是因为您在导入时没有引用 ValidationError。 ValidationError 不是 pymongo 将抛出的异常,因此您可以将其更改为更通用的

      except Exception as e:
    

    它抛出错误的原因是因为您在应该插入 JSON 时尝试插入字符串。即使它看起来像 JSON,您也必须使用 json.loads 将其转换为 JSON。

    collection.insert_one(json.loads(document))
    

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2012-05-29
      • 2013-08-23
      • 2014-04-03
      • 2017-05-12
      相关资源
      最近更新 更多