官方文档https://dormousehole.readthedocs.io/en/latest/patterns/mongoengine.html。
1安装flask-mongoengine
推荐使用pip进行安装,如果无法联网也可通过离线方式进行安装,首先下载准备好flask-mongoengine,mongoengine,pymongo,flask-wtf,wtforms,dnspython,email_validator,idna等依赖包,然后依次安装即可。
2配置
基本配置如下:
from flask import Flask
from flask_mongoengine import MongoEngine
...
app = Flask(__name__)
#your other code
app.config['MONGODB_DB'] = 'project1' #your database name
app.config['MONGODB_HOST'] = '192.168.1.35' #your remote host
app.config['MONGODB_PORT'] = 12345 #port
app.config['MONGODB_USERNAME'] = 'webapp' #username
app.config['MONGODB_PASSWORD'] = 'pwd123' #password
mongo = MongoEngine(app)
如果使用了工厂方法,则如下配置:
from flask import Flask
from flask_mongoengine import MongoEngine
mongo = MongoEngine()
...
app = Flask(__name__)
#your other code
app.config['MONGODB_DB'] = 'project1' #your database name
app.config['MONGODB_HOST'] = '192.168.1.35' #your remote host
app.config['MONGODB_PORT'] = 12345 #port
app.config['MONGODB_USERNAME'] = 'webapp' #username
app.config['MONGODB_PASSWORD'] = 'pwd123' #password
mongo.init_app(app)
3.映射文档
首先声明model,与mongodb中的文档相对应。方法是创建一个 Document 的子类,然后 声明每个字段:
import mongoengine as me
class Movie(me.Document):
title = me.StringField(required=True)
year = me.IntField()
rated = me.StringField()
director = me.StringField()
actors = me.ListField()
4.查询
flask-mongoengine非常智能,直接使用类的 objects 属性即可执行查询。关键字参数用于字段的等值查询:
bttf = Movies.objects(title="Back To The Future").get()
如果要查询所有,可通过迭代的方式获取:
for movie in Movies.objects():
#your operations
其他增删改操作不再赘述,需要可自行搜索。