First:
I'm working on a flask project and using msql for now, but want to migrate to sqlalchemy. I want to access existing database table using sqlalchemy. Does sqlalchemy have any alternative for something like this
python manage.py inspectdb > models.py
which we use in django.
I tried to test this solution, so my script is like this now:
from flask import Flask, render_template
from itertools import groupby
from flask import request
import MySQLdb
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
Base = automap_base()
engine = create_engine("mysql://myusername:mypassword@localhost/mydbname")
Base.prepare(engine, reflect=True)
User = Base.classes.p_user
session = Session(engine)
session.commit()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myusername:mypassword@localhost/mydbname'
db = SQLAlchemy(app)
@app.route('/test/')
def test():
result = str(session.query(User).all())
return result
if __name__ == '__main__':
app.run()
But the output is like this:
[, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
Why? And how I can fix it?
Second:
Also how should I use filter for selecting data in my script?
I tried this:
result = session.query(User).filter_by(shahr = 'tehran')
But this arror raised in terminal:
TypeError: 'Query' object is not callable
Also tried this one:
result = session.query.filter_by(shahr = 'tehran')
The error:
AttributeError: 'function' object has no attribute 'filter_by'
Or tried this one:
result = User.query.filter_by(shahr = 'tehran')
And the error was:
AttributeError: type object 'p_user' has no attribute 'query'