chaos.ct
chaos.ct

Reputation: 1091

Python Eve, SQLalchemy and ForeignKey

I am working in a Python Eve based RESTful service with a SQLAlcemy backend. I have two models with a one to many relationship:

class User(CommonColumns):

    """Model of an user in the database"""
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    username = Column(String, unique=True)
    email = Column(EmailType, unique=True)
    folders = relationship('Folder', backref='user')

    def __unicode__(self):
        return self.username


class Folder(CommonColumns):

    """Model of an user in the database"""
    __tablename__ = "folder"
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    user_id = Column(Integer, ForeignKey('user.id'), nullable=False)

    def __unicode__(self):
        return "{}/{}".format(self.user.username, self.name)

CommonColumnsis defined like here

This works great when inserting, updating and deleting users. However, I can't get inserting right for folders:

newfolder = {
'name':'FOLDER',
 'user_id': 1,
}
response = requests.post("http://localhost:8080/api/v1.0/folders",data=newfolder)
print response.json()

{u'_error': {u'code': 422,
  u'message': u'Insertion failure: 1 document(s) contain(s) error(s)'},
 u'_issues': {u'exception': u"'user'"},
 u'_status': u'ERR'}

Which is a rather cryptic error message. I've been reading Python Eve's documentation and I can't really understand what I am doing wrong. The only difference I see between user and folder insertions is that one has foreign keys.

Any idea why this is happening?

Upvotes: 5

Views: 644

Answers (1)

chaos.ct
chaos.ct

Reputation: 1091

Well, it seemed that the problem was that I didn't have the same name for the resource and the table name ("users" for resource, "user" for table name). This seems to raise problems with foreign keys in eve, but does not fail with entities without relationships.

Changing the table names to match the resource names solved the problem.

I hope this will be useful to anyone.

Upvotes: 5

Related Questions