Forums

Sqlalchemy does not create table

sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1146, "Table 'myname$default.users' doesn't exist") 'INSERT INTO users (username, password_hash) VALUES (%s, %s)'

I get this error I use flask with python 3.4 and pymysql I do

if __name__ == '__main__':
    db.create_all()

it was working on localhost with sqlite it does not work on pythonanywhere neither sqlite nor mysql

Thank you

[edited by admin: formatting]

do you mean that you get that error when you try to run db.create_all()?

Yes I think db.create_all() does not create tables thats what I understand do I have to create tables manually

I'm imagining all your code is in a file called flask_app.py, or something similar.

When you run that file on your own PC, with

python flask_app.py

Then __name__ == '__main__' is True, and Python will run the db.create_all(), and also the flask debug server I expect (do you have an app.run() inside that block too?)

When you run on pythonanywhere though, we run the code for you by importing it, and in that case if __name__ == '__main__' is False, which is good because we don't want to use the flask debug server, we want to use the pythonanywhere production servers.

So, two solutions:

  • either move the db.create_all() outside the if block -- that's probably a bad idea, because it'll get run every time that file is imported, which is probably more often that you want

  • or, run the file manually, whenever you make changes to your database, in a pythonanywhere Bash console:

    python flask_app.py

(you'll probably need to hit ctrl+c to kill the flask dev server, but by then it will have run the create_all())

Hope that makes sense?

Thank you I did your suggestion and it worked I run the flask_app.py in Bash console

Great! Remember, you'll need to run it any time you make a change to the database schema (adding new tables, or new columns to existing tables)