Reputation: 1675
I'm needing to implement an API for my Flask application and have seen recommendations for Flask-Restless
. I've run in to kind of a wall with just basic usage of this library and hoping someone who has used it can assist.
Creating the API manager and endpoints...
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Gallery, methods=['GET', 'POST', 'PUT', 'DELETE'])
...and the model that goes with that
class Gallery(db.Model):
__tablename__ = 'galleries'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(25))
def __init__(self, title):
self.title = title
Now, to insert new entries, I use this jQuery ajax POST request. This works fine. I've tested it in a sqlite db viewer and can see the entries.
$('#form').on('submit', function(e){
$.ajax({
type: 'post',
url: '/api/galleries',
contentType:"binary/octet-stream",
data: JSON.stringify({'title': $('#title').val()}),
success: function(){
alert('Success!');
}
});
e.preventDefault();
});
Here's the issue. I go to http://localhost:5000/api/galleries
in my browser and get the following message:
sqlalchemy.orm.exc.NoResultFound
NoResultFound: No row was found for one()
Its odd it would try to run one() when api/galleries
should return a list of db entries. I try api/galleries/1
and get the exact same error. I double checked and the primary id is 1. What am I missing?
Upvotes: 1
Views: 572
Reputation: 1258
I got the same issue today and solved it with some workaround.
Here is what my models look like:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
...
class Key(db.Model):
user_id = db.Column(db.Integer, db.ForeignKey('auth_user.id'))
user = db.relationship('User', backref=db.backref('keys', lazy='dynamic'))
...
Cause:
I got the same error message when querying users
. And I found that flask-restless is trying to query the related keys
for my users
and unfortunately, my key
table is empty and I got the error message.
Workaround:
Use include_columns or exclude_columns to exclude the keys
column when creating APIs:
api_mgr.create_api(User, include_columns = ['email', 'username'])
or:
api_mgr.create_api(User, exclude_columns = ['keys', 'SOME_OTHER_COLUMNS'])
You can check out if there is any related tables causing the problem. And if it is the cause, you can using include_columns or exclude_columns keyword arguments.
Upvotes: 1