Declare model before create connection in ming

大城市里の小女人 提交于 2019-12-23 03:48:08

问题


I want delcare my models before make connection with database (for some reason like multi-threading, and dynamic load of database config uri).

Documentation say to use like that:

from ming import create_datastore
from ming.odm import ThreadLocalODMSession
from ming import schema
from ming.odm import FieldProperty
from ming.odm.declarative import MappedClass

session = ThreadLocalODMSession(
    bind=create_datastore('odm_welcome')
)

class WikiPage(MappedClass):
    class __mongometa__:
        session = session
        name = 'wiki_page'

    _id = FieldProperty(schema.ObjectId)
    title = FieldProperty(schema.String(required=True))
    text = FieldProperty(schema.String(if_missing=''))

We can see what model declaration need session (in __mongometa__). How can i declare WikiPage model without session variable ? And set it later ?


回答1:


Solution can be declare model without __mongometa__:

class WikiPage(MappedClass):
    _id = FieldProperty(schema.ObjectId)
    title = FieldProperty(schema.String(required=True))
    text = FieldProperty(schema.String(if_missing=''))

Then make make mapping manually with a collection:

session = ODMSession(bind=create_datastore(uri))
collection_ = collection('wiki_page', session)
session.mapper(WikiPage, collection_)


来源:https://stackoverflow.com/questions/41807329/declare-model-before-create-connection-in-ming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!