1

SQLAlchemy、Marshmellow、および Flask を使用して既に作成されたコードに取り組む必要があり、新しいユーザーをデータベースに追加しようとしています。私はまだコードを研究して、それが機能するかどうかを判断しようとしていますが、データベースに新しいエントリを追加しようとすると、いつでも例外が呼び出されます 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.session.add(user) ができるので、dbがつながっているようです これが完全なトレースバックです

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}]
4

0 に答える 0