title: Creating dynamic documents in Flask-MongoAlchemy
body: <p>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.</p>
  
  <p>Here's my input .cfg file. I'd like to make this into multiple mongodb documents.</p>
  
  <pre><code>[foo]
  a = val1
  b = val2
  c = val3
  d = val4
  </code></pre>
  
  <p>Here's documents.cfg that defines the structure. The values are numbers to distinguish types.</p>
  
  <pre><code>[foo]
      [[bar]]
      a = 1
      b = 1
      [[baz]]
      c = 2
      d = 1
  </code></pre>
  
  <p>Here are the class definitions</p>
  
  <pre class="lang-py prettyprint-override"><code>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())
  </code></pre>
  
  <p>I parse documents.cfg to create two dicts:</p>
  
  <pre><code>bar_dict = {'a': '1', 'b': '1'}
  baz_dict = {'c': '2', 'd': '1'}
  </code></pre>
  
  <p>I then pass these to the respective init() methods</p>
  
  <pre><code>Bar.init(**bar_dict)
  Baz.init(**baz_dict)
  </code></pre>
  
  <p>This successfully adds the attributes. However, when creating an instance of Bar (or Baz) I get this error.</p>
  
  <pre><code>mongoalchemy.exceptions.ExtraValueException: a
  </code></pre>
  
  <p>My guess is that this has to do with the fact that the MongoAlchemy fields should be class attributes, not instance attributes. Any help?</p>