Flask sqlalchemy.exc.OperationalError: (OperationalError) no such table when trying to update database with SQLAlchemy

后端 未结 3 643
心在旅途
心在旅途 2021-01-25 13:31

I\'m new to Flask, and having some issues setting up a very basic Flask app. Right now, I\'m trying to get the user to submit a form on the homepage and then save that form to

3条回答
  •  无人共我
    2021-01-25 13:58

    I had the same issue. In my case I was querying the database in a forms.py and this was imported to routes.py.

    So the problem was basically that the database was queried in the code before it could be created, as classes are loaded before the server starts and an eventual init happens.

    The accepted answer didn't work for me. Unfortunately, I haven't found a clean solution for this. So I ended up with a workaround for this.

    In my case I wanted to show files in a dropdown list, so I initialized them empty the first time:

    try:
        profile_files = [ (file.path, file.filename[:-4])
                            for file in File.query.filter_by(type=2).order_by(File.created.desc()).all()]
    except sqlalchemy.exc.OperationalError as e:
        profile_files = []
    

    So the general workaround would be:

    try:
        # Your DB query
    except sqlalchemy.exc.OperationalError as e:
        # create placeholder until your DB is ready
    

    Now I can use all the terminal commands again:

    flask db init
    flask db migrate
    flask db upgrade
    

    Hope this is helpful to someone!

提交回复
热议问题