简体   繁体   中英

Flask-SQLAlchemy: Can't query from User database

I am trying to create an endpoint on my Flask app that will show all user info (I know this is unsafe, its for debugging).

I have created the route with the following code:

@main_bp.route('/users', methods=['GET'])
@login_required
def userInfo():
    from .models import User
    q = User.query.all()
    return str(q)

This ends up returning [] , while I know for a fact that there are users in the database. Further, when selecting a single record, I am able to get the username as follows:

def userInfo():
    from .models import User
    q = User.query.first()
    return str(q.username)

I am using SQLite3, but plan to move to PostgreSQL soon, so if the problem lies within SQLite, the ideal solution would be to just connect to a PG database instead.

This is certainly a weird error. Try looping through q and adding the names to double check like so:

@main_bp.route('/users', methods=['GET'])
@login_required
def userInfo():
    from .models import User
    users = User.query.all()
    result = ''
    for u in users:
        result += str(u.username)

    return result

See if you get anything there.

Your code is working for me. I have also a "User" in sqlalchemy, and if I copy your code, I only have to change the name of the app, and it works:

@app.route('/users', methods=['GET'])
@login_required
def userInfo():
  from .models import User
  q = User.query.all()
  return str(q)

If you are sure that you have users in the DB, maybe this code is not executed? Something weird: redundant route?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM