sqlalchemy的神秘错误:TypeError' User'对象不可调用

时间:2016-12-02 22:48:42

标签: python mysql api flask sqlalchemy

我正在尝试使用flask和sqlalchemy链接到MySQL数据库创建一个简单的应用程序。我在我的数据库中创建了一个带有一些虚拟数据的User表,并且我试图在我的/ api路由上测试一个示例查询。我不断收到内部服务器错误,而且在我的生活中无法弄清楚发生了什么。我之前制作了一个类似于此的应用,它从来没有给我这个奇怪的错误。堆栈跟踪如下:

2016-12-02 22:15:16,079 - app - ERROR - Exception on /api [GET]
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
        response = self.full_dispatch_request()
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1642, in full_dispatch_request
        response = self.make_response(rv)
      File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1746, in make_response
        rv = self.response_class.force_type(rv, request.environ)
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 847, in force_type
        response = BaseResponse(*_run_wsgi_app(response, environ))
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
        return _run_wsgi_app(*args)
      File "/usr/local/lib/python2.7/dist-packages/werkzeug/test.py", line 871, in run_wsgi_app
        app_rv = app(environ, start_response)
    TypeError: 'User' object is not callable

app.py

from flask import Flask
from database.models import User
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine

engine = create_engine('mysql://root:123pass@localhost/testdb', convert_unicode=True)

Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Create a scoped session
ssession = scoped_session(Session)

app = Flask(__name__)


# Setup our error logging
if app.debug is not True:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('errors.log', maxBytes=1024 * 1024 * 100, backupCount=20)
    file_handler.setLevel(logging.ERROR)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)


@app.route('/')
def index():
    return 'hello world'


@app.route('/api')
def api_route():
    # Error is happening right here
    return ssession.query(User).first()


if __name__ == '__main__':
    app.run(debug=False)

数据库/ models.py

from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, BLOB, \
    DateTime, ForeignKey

Base = declarative_base()

class User(Base):
    __tablename__ = 'User'

    id = Column(Integer, primary_key=True)
    email = Column(String(64), unique=True)
    password = Column(String(255))
    join_date = Column(DateTime)
    last_login = Column(DateTime)
    login_count = Column(Integer, default=0)
    name = Column(String(128), default=None)
    location = Column(String(128), default=None)
    points = Column(Integer, default=0)
    num_posts = Column(Integer, default=0)

    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.join_date = datetime.utcnow()
        self.last_login = datetime.utcnow()

    def __repr__(self):
        return '<User %r>' % self.email

我不知道为什么这不起作用 - 如果我导入所有必要的模块,它在python控制台中实际上完全正常工作!任何见解都会很棒。

1 个答案:

答案 0 :(得分:0)

return ssession.query(User).first()

您正在尝试返回不允许的User对象。您需要返回其他类型。作为一个非常简单的示例,下面将返回用户的电子邮件。

return ssession.query(User).first()['email']

您可能希望返回用户的JSON表示,为此我会查看Flask-Marshmallow。