I'm using Flask-MongoAlchemy for a personal project. I have some .cfg input files that I want to parse and make into mongodb document entries. Unfortunately, the .cfg files are flat and I want to make multiple different documents from each file. I'd like to define the structure I want to use in one place (in a separate .cfg file) and 1) convert the input files into this format while parsing it, and 2) create the MongoAlchemy document classes using this structure. I'm only having troubles with #2, but I am open to alternative implementations that solve both goals.
Here's my input .cfg file. I'd like to make this into multiple mongodb documents.
[foo]
a = val1
b = val2
c = val3
d = val4
Here's documents.cfg that defines the structure. The values are numbers to distinguish types.
[foo]
[[bar]]
a = 1
b = 1
[[baz]]
c = 2
d = 1
Here are the class definitions
class Bar(db.Document):
# add class attributes from kwargs
@classmethod
def init(cls, **kwargs):
for k, v in kwargs.items():
if v == 1:
setattr(cls, k, db.IntField(min_value=0))
class Baz(db.Document):
# add class attributes from kwargs
@classmethod
def init(cls, **kwargs):
for k, v in kwargs.items():
if v == 1:
setattr(cls, k, db.IntField(min_value=0))
elif v == 2:
setattr(cls, k, db.StringField())
I parse documents.cfg to create two dicts:
bar_dict = {'a': '1', 'b': '1'}
baz_dict = {'c': '2', 'd': '1'}
I then pass these to the respective init() methods
Bar.init(**bar_dict)
Baz.init(**baz_dict)
This successfully adds the attributes. However, when creating an instance of Bar (or Baz) I get this error.
mongoalchemy.exceptions.ExtraValueException: a
My guess is that this has to do with the fact that the MongoAlchemy fields should be class attributes, not instance attributes. Any help?