플래스크 169페이지 , 진행중 문의 사항 (에러문의 드려요)
class Answer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id', ondelete='CASCADE'))
    question = db.relationship('Question', backref=db.backref('answer_set'))
    content = db.Column(db.Text(), nullable=False)
    create_date = db.Column(db.DateTime(), nullable=False)
   user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=True, server_default='1')
    user = db.relationship('User', backref=db.backref('answer_set'))

이렇게 책에 적힌대로 수정을 하고
cmd에서
flask db migrate
하고
flask db upgrade 하니 , upgrade 가 오류가 나더라구요

그래서 지금 한 한시간넘게 이것저것 해본상태 인데, 해결이 안되서 문의 드립니다.

제가 생각하는 해결 방안은
이전페이지에서 배운 대로

flask db stamp heads 를 하고

다시
flask db migrate
flask db upgrade
를 진행하는것인데

flask db migrate 하면

(myproject) C:\projects\myproject>flask db migrate
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected removed table '_alembic_tmp_answer'
INFO  [alembic.autogenerate.compare] Detected NOT NULL on column 'answer.user_id'
Generating C:\projects\myproject\migrations\versions\8ab45f07d81a_.py ...  done

이렇게 출력 결과가 잘나오는데

flask db upgrade 하면

(myproject) C:\projects\myproject>flask db upgrade
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade 70ea9a2867b0 -> 8ab45f07d81a, empty message
Traceback (most recent call last):
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: NOT NULL constraint failed: _alembic_tmp_answer.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ceo\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\ceo\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\venvs\myproject\Scripts\flask.exe\__main__.py", line 9, in <module>
  File "c:\venvs\myproject\lib\site-packages\flask\cli.py", line 967, in main
    cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
  File "c:\venvs\myproject\lib\site-packages\flask\cli.py", line 586, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "c:\venvs\myproject\lib\site-packages\click\core.py", line 782, in main
    rv = self.invoke(ctx)
  File "c:\venvs\myproject\lib\site-packages\click\core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "c:\venvs\myproject\lib\site-packages\click\core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "c:\venvs\myproject\lib\site-packages\click\core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\venvs\myproject\lib\site-packages\click\core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "c:\venvs\myproject\lib\site-packages\click\decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "c:\venvs\myproject\lib\site-packages\flask\cli.py", line 426, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "c:\venvs\myproject\lib\site-packages\click\core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "c:\venvs\myproject\lib\site-packages\flask_migrate\cli.py", line 136, in upgrade
    _upgrade(directory, revision, sql, tag, x_arg)
  File "c:\venvs\myproject\lib\site-packages\flask_migrate\__init__.py", line 96, in wrapped
    f(*args, **kwargs)
  File "c:\venvs\myproject\lib\site-packages\flask_migrate\__init__.py", line 271, in upgrade
    command.upgrade(config, revision, sql=sql, tag=tag)
  File "c:\venvs\myproject\lib\site-packages\alembic\command.py", line 294, in upgrade
    script.run_env()
  File "c:\venvs\myproject\lib\site-packages\alembic\script\base.py", line 481, in run_env
    util.load_python_file(self.dir, "env.py")
  File "c:\venvs\myproject\lib\site-packages\alembic\util\pyfiles.py", line 97, in load_python_file
    module = load_module_py(module_id, path)
  File "c:\venvs\myproject\lib\site-packages\alembic\util\compat.py", line 182, in load_module_py
    spec.loader.exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "migrations\env.py", line 96, in <module>
    run_migrations_online()
  File "migrations\env.py", line 90, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "c:\venvs\myproject\lib\site-packages\alembic\runtime\environment.py", line 813, in run_migrations
    self.get_context().run_migrations(**kw)
  File "c:\venvs\myproject\lib\site-packages\alembic\runtime\migration.py", line 560, in run_migrations
    step.migration_fn(**kw)
  File "C:\projects\myproject\migrations\versions\8ab45f07d81a_.py", line 23, in upgrade
    batch_op.alter_column('user_id',
  File "C:\Users\ceo\AppData\Local\Programs\Python\Python38\lib\contextlib.py", line 120, in __exit__
    next(self.gen)
  File "c:\venvs\myproject\lib\site-packages\alembic\operations\base.py", line 336, in batch_alter_table
    impl.flush()
  File "c:\venvs\myproject\lib\site-packages\alembic\operations\batch.py", line 118, in flush
    batch_impl._create(self.impl)
  File "c:\venvs\myproject\lib\site-packages\alembic\operations\batch.py", line 366, in _create
    op_impl._exec(
  File "c:\venvs\myproject\lib\site-packages\alembic\ddl\impl.py", line 146, in _exec
    return conn.execute(construct, multiparams)
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\base.py", line 1011, in execute
    return meth(self, multiparams, params)
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\sql\elements.py", line 298, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\base.py", line 1124, in _execute_clauseelement
    ret = self._execute_context(
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\base.py", line 1316, in _execute_context
    self._handle_dbapi_exception(
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\base.py", line 1510, in _handle_dbapi_exception
    util.raise_(
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_
    raise exception
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "c:\venvs\myproject\lib\site-packages\sqlalchemy\engine\default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: _alembic_tmp_answer.user_id
[SQL: INSERT INTO _alembic_tmp_answer (id, question_id, content, create_date, user_id) SELECT answer.id, answer.question_id, answer.content, answer.create_date, answer.user_id
FROM answer]
(Background on this error at: http://sqlalche.me/e/13/gkpj)

이렇게 에러 메세지가 나오네요.구글링으로도 해결못하고있네요
방법알려주시면 감사하겠습니다.

ilue00 614

2021년 2월 21일 3:04 오후

목록으로
1개의 답변이 있습니다. 1 / 1 Page

flask db migrate 시 answer.user_id 에 이미 Not Null로 컬럼을 추가하신것 같네요.
책에서는 Null 허용으로 추가하는걸로 되어 있습니다. 이후 다시 Not null로 바꾸어주는 방법입니다.

만약 이미 Not null로 추가하셨다면 Question에 했던것과 동일한 방법으로 해 주셔야 합니다.

이렇게 저렇게 다 안될 경우에는 sqlite3 파일을 아예 삭제하시고 flask db init 부터 시작하셔도 됩니다. (단, 이 경우에는 모든 데이터가 사라지니 주의해 주세요.)

박응용

2021년 2월 21일 4:02 오후

sqlite3 파일은 어디서 삭제하나요? - cezips님, 2023년 1월 3일 12:04 오전 추천 , 대댓글