切換數(shù)據(jù)存儲
flask-mongoengine好像在配置文件中配置好了以后牵祟,就不能改變數(shù)據(jù)庫配置了抖格,所以我直接使用mongoengine來配置的
先申明連接數(shù)據(jù)
connect(db=remote_db,
host=remote_host,
username=remote_username,
password=remote_password,
alias='remote_db')
connect(db=local_db,
host=local_host,
username=local_username,
password=local_password,
alias='local_db')
alias作為連接區(qū)分,一個本地數(shù)據(jù)收奔,一個遠程數(shù)據(jù)庫滓玖,并且在class類中要加上meta參數(shù),順便一說呢撞,如果要改變儲存的collection可以在meta里面改參數(shù)
class Student(Document):
name = StringField(required=True)
student_id = StringField(required=True)
class_id = StringField(required=True)
address_mac = StringField(required=True)
meta = {'db_alias': 'local_db', 'collection': 'student_info_remote'}
使用switch_db改變連接的數(shù)據(jù)庫
with switch_db(Student, 'remote_db') as Student: #第一個參數(shù)是要改變連接的表名殊霞,第二個是要連接的已經(jīng)定義好的數(shù)據(jù)庫