0

I've been using mongoengine for a while now and have a ton of python data processing code that relies on a common set of Object Document Models.

Now I need to access the same mongodb instances from Flask. I'd like to use the same ODM definitions.

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

The problem is that flask-mongoengine requires you to first set up your flask context "db" and then build your ODM definitions, inheriting the document class and fieldtypes from "db" instead of the base mongoengine classes.

class User(db.Document):
    email = db.StringField(required=True)
    first_name = db.StringField(max_length=50)
    last_name = db.StringField(max_length=50)

One solution, I suppose, is to make copies of all of the existing ODM definitions, import "db" from my main flask app, and then prepend everything with "db." If I do that, I'll have to maintain two sets of nearly identical ODM definitions.

If I simply change everything to the "db." version, that would probably break all of my legacy code.

So I'm thinking there might be a trick using super() on the document classes that can detect whether I'm importing my ODM into a Flask context or whether I'm importing it from a stand alone data processing script.

I'm also thinking I don't want to have to super() every fieldtype for every document, that I should be able to build or reference a common function that took care of that for me.

However, my super() skills are weak. I'm not even certain if that is the best approach. I was hoping someone might be able and willing to share some hints as to how to approach this.

rotten
  • 1,580
  • 19
  • 25
  • 1
    I've run into this issue myself and as you suggest if you want to use the same models in a flask context and a non-flask context it can be tricky. However, all flask-mongoengine is doing is making sure that the mongodb connection is based on the app configuration. My solution was to not use flask-mongoengine at all and just create the connection to mongodb myself in the config file. – Steve Rossiter Jan 27 '16 at 14:19
  • [I'm not sure why this question was downvoted.] I think the way I'm going to work around this issue is to use a PostgreSQL Foreign Data Wrapper, and then query the MongoDB collections with SQLAlchemy like any of my other PostgreSQL tables. – rotten Sep 26 '16 at 18:42

0 Answers0