为什么我的sqlalchemy模型无法调用?

时间:2017-06-05 19:36:16

标签: python

我正在关注official sqlalchemy tutorial开始,但是当我尝试实例化下面的User类时,解释器告诉我它不可调用。我不知道为什么。有人有任何想法吗?

__初始化__。PY

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

user.py

from sqlalchemy import Column, Integer, String

from __init__ import Base


class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

user_api.py

from flask import request
from flask.views import MethodView

from src.main.model.user import User


class UserAPI(MethodView):
    def post(self):
        usr = User(**request.form)
        return usr

__主__。PY

import flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from src.main.endpoints.user_api import UserAPI
from src.main.model import Base

def database_stuff():
    engine = create_engine('sqlite:///:memory:', echo=True)
    Session = sessionmaker(bind=engine)
    Base.metadata.create_all(engine)

if __name__ == "__main__":
    database_stuff()
    app = flask.Flask(__name__)
    user_view = UserAPI.as_view("users")
    app.add_url_rule("/users/", defaults={"user_id": None}, view_func=user_view, methods=["GET"])
    app.add_url_rule("/users/", view_func=user_view, methods=["POST"])
    app.add_url_rule("/users/<int:user_id>", view_func=user_view, methods=["GET"])
    app.run()

当尝试向Flask服务器发出请求时,这就是我在日志中获得的内容:

Traceback (most recent call last):
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\flask\app.py", line 1740, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\wrappers.py", line 885, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "D:\Documents\python\flaskplay\flaskplay\lib\site-packages\werkzeug\test.py", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'User' object is not callable
127.0.0.1 - - [05/Jun/2017 20:44:32] "POST /users/ HTTP/1.1" 500 -

1 个答案:

答案 0 :(得分:1)

它实际上与sqlalchemy无关。该对象确实是可调用的和可实例化的。尝试将对象作为响应返回时,实际上会出现错误。您无法从Flask端点返回任何旧对象。如果我将对象dict转换为json,则错误不再适用。