SQLAlchemy尝试在主键上插入空值

时间:2017-10-17 11:48:37

标签: python flask sqlalchemy flask-sqlalchemy marshmallow

我必须使用SQLAlchemy,Marshmellow和Flask处理已编写的代码,并尝试将新用户添加到数据库中。我还在研究代码,试图找出它是否有效,但是当我尝试向db添加新条目时,它会将其称为异常 sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "id" violates not-null constraint 这是我的SQLAlchemy模型user.py

from .. import db
class User(db.Model):
  __tablename__ = 'user'

  id = db.Column(db.Integer, primary_key=True)
  age = db.Column(db.Integer)
  gender = db.Column(db.String)
  region = db.Column(db.String)
  date_created  = db.Column(db.DateTime,  default=db.func.current_timestamp())

  def __init__(self, age, gender, region):
    self.age = age
    self.gender = gender
    self.region = region

  def __repr__(self):
    return '<User {1}>'.format(self.id)

这是管理POST操作的api

@api.route('/users', methods=['POST'])
def create_user():
  print("debug")
  json_data = request.get_json()
  print(json_data)
  if not json_data:
    return jsonify({'message': 'Invalid Request'}), 400
  # Validate and deserialize input
  user,errors = user_schema.load(json_data)
  if errors:
    return jsonify(errors), 422
  # save new user to db
  new_user = User(user.age,user.gender,user.region)
  print(user.age)
  db.session.add(new_user)
  if db.session:
    db.session.commit()
  initialize(0, user)
  print("wtf")
  return jsonify({"message": "Created new user.",
                "user": json_data}), 201

它总是有提交问题 我该如何解决?我正在失去理智 的修改

似乎db已连接,因为我可以毫无问题地执行db.session.add(user) 这是完整的追溯

Traceback (most recent call last):
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/leonardo/.local/lib/python3.5/site-
packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/leonardo/.local/lib/python3.5/site-
packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/home/leonardo/.local/lib/python3.5/site-packages/flask/app.py", 
line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/leonardo/Università/Tirocinio/tim-recommender-
api/app/api/user.py", line 44, in create_user
db.session.commit()
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/session.py", line 801, in commit
self.transaction.commit()
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/session.py", line 392, in commit
self._prepare_impl()
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/session.py", line 372, in _prepare_impl
self.session.flush()
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/session.py", line 2019, in flush
self._flush(objects)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/session.py", line 2137, in _flush
transaction.rollback(_capture_exception=True)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/session.py", line 2101, in _flush
flush_context.execute()
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/persistence.py", line 174, in save_obj
mapper, table, insert)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/orm/persistence.py", line 800, in 
_emit_insert_statements
execute(statement, params)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/sql/elements.py", line 323, in 
_execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/engine/base.py", line 1010, in 
_execute_clauseelement
compiled_sql, distilled_params
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/engine/base.py", line 1146, in _execute_context
context)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/engine/base.py", line 1341, in 
_handle_dbapi_exception
exc_info
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/util/compat.py", line 185, in reraise
raise value.with_traceback(tb)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
context)
File "/home/leonardo/.local/lib/python3.5/site-
packages/sqlalchemy/engine/default.py", line 450, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in 
column "id" violates not-null constraint
DETAIL:  Failing row contains (null, 19, Male                                              
, Basilicata                                        , 2017-10-25 
09:40:42.880058).
[SQL: 'INSERT INTO "user" (age, gender, region, date_created) VALUES 
(%(age)s, %(gender)s, %(region)s, CURRENT_TIMESTAMP) RETURNING 
"user".id'] [parameters: {'region': 'Basilicata', 'gender': 'Male', 
'age': 19}]

0 个答案:

没有答案