I’m trying to build a small MSA system.
It has 3 micro services build with python, Flask and SQLAlchemy.
I have users table and user_quest_rewards table, which are in separate databases in separate micro services.
I need to use user_id column from users table as foreign key of user_quest_rewards table.
Here is what I tried in python:
class UserQuestReward(Base):
__tablename__ = 'user_quest_rewards'
user_id = Column(Integer)
quest_id = Column(Integer)
status = Column(Enum('claimed', 'not_claimed'))
date = Column(TIMESTAMP)
user = relationship("User", back_populates="quest_rewards", foreign_keys=[user_id])
class User(Base):
__tablename__ = 'users'
user_id = Column(Integer, primary_key=True)
user_name = Column(String)
password = Column(String)
gold = Column(Integer)
diamond = Column(Integer)
status = Column(Enum('new', 'not_new', 'banned'))
quest_rewards = relationship("UserQuestReward", back_populates="user")
I thought ‘relationship’ method of SQLAlchemy would link two separate tables but it doesn’t work. Maybe it’s because they are in separate database.
These microservices are placed in separate docker container, routed by API gateway with nginx.
When I try to insert a row to users table, it spits following error:
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper[User(users)], expression 'UserQuestReward' failed to locate a name ('UserQuestReward'). If this is a class name, consider adding this relationship() to the <class 'models.User'> class after both dependent classes have been defined.
I have tried ForeignKey() and ForeignKeyConstraint as well but somehow it didn’t work out. What should I do with making foreign key between two separated DBs?
I have tried ForeignKey() and ForeignKeyConstraint as well but somehow it didn’t work out. What should I do with making foreign key between two separated DBs?