Flask AttributeError:“ NoneType”对象没有属性“名称”

时间:2020-07-11 15:34:53

标签: python flask-sqlalchemy

正在开发一个简单的Web应用程序,该应用程序应返回“ Hello,(从数据库中提取名称)”。就是说the object has no attribute for 'name' 即使name在类中被列为属性。无法弄清楚为什么它认为不存在(除非我误解了错误)?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app=Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres@localhost:5432/example'
db = SQLAlchemy(app)

# initalizes the class/table
class Person(db.Model):
    __tablename__ = 'persons'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False)

db.create_all()

@app.route('/')
def index():
    person = Person.query.first()
    return 'Hello ' + person.name

错误:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/ZEMEL/Dropbox (Personal)/Code/hello/flask-hello-app.py", line 20, in index
    return 'Hello ' + person.name
AttributeError: 'NoneType' object has no attribute 'name'

1 个答案:

答案 0 :(得分:0)

您的数据库中没有内容,或者您​​以错误的方式获取数据。

person=Person.query(name="name").first() 

应该以名字为“ name”的第一个人来获取数据