A
A
Archet2014-12-28 23:12:03
Flask
Archet, 2014-12-28 23:12:03

Why does SQLAlchemy behave this way?

So, there is the smallest project on Flask + SQLAlchemy.

App.py

from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy as SA

SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://user:[email protected]:3306/app_db'
app = Flask(__name__)
db = SA(app)

from sqlalchemy import create_engine
engine = create_engine(SQLALCHEMY_DATABASE_URI)
db.metadata.reflect(engine)   

from Classes import *

@app.route('/')
def get_index():
    Users.query.all()
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)
    pass


classes.py
from App import db
class Users(db.Model):
    __table__ = db.metadata.tables['users']


SQLAlchemy obviously correctly reads the metadata from the existing MySQL database, however, when trying to access the data in Users.query.all(), it complains about the absence of such a table, although 10 lines before that it successfully read the structure of this table.

sqlalchemy.exc.OperationalError: (OperationalError) no such table: users 'SELECT users."UserId" AS "users_UserId", users."UserLogin" AS "users_UserLogin", users."UserPassword" AS "users_UserPassword", users."UserMail " AS "users_UserMail", users."UserType" AS "users_UserType" \nFROM users' ()


In addition to this, if you dig a little up the error stack, you can see that context.engine == Engine(sqlite://).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ismailov, 2015-01-01
@Archet

You need to read the documentation for ext.sqlalcmemy a little more carefully.
You use a wrapper, but you declare the engine somewhere away from it.
And you also specify the URI to the base aside from app.
It should be like this:

from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy as SA

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://user:[email protected]:3306/app_db'
db = SA(app)

from sqlalchemy import create_engine

db.metadata.reflect(db.engine)
from Classes import *

@app.route('/')
def get_index():
    Users.query.all()
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)
    pass

And then everything will work fine

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question