1

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'

Community
  • 1
  • 1
Andishe
  • 115
  • 1
  • 3
  • 12
  • 1
    I found the solution myself `sqlacodegen postgresql://postgres:mydbpassword@localhost/mydb --outfile db.py` ... this page helps `https://simpletutorials.com/c/2220/SQLAlchemy+Code+Generation` – Andishe Aug 02 '16 at 11:34

0 Answers0