有人使用过 MongoKit、MongoEngine 或 Flask-MongoAlchemy for Flask 吗?
你更喜欢哪一个?积极或消极的经历? Flask-Newbie 的选择太多。
最佳答案
我投入了大量时间来评估流行的 MongoDB 的 Python ORM。这是一个详尽的练习,因为我真的很想选择一个。
我的结论是 ORM 消除了 MongoDB 的乐趣。没有一种感觉是自然的,它们施加的限制类似于让我从一开始就离开关系数据库的限制。
再次,我真的很想使用 ORM,但现在我确信直接使用 pymongo
是可行的方法。现在,我遵循包含 MongoDB、pymongo
和 Python 的模式。
面向资源的架构导致非常自然的表示。例如,获取以下用户资源:
from werkzeug.wrappers import Response
from werkzeug.exceptions import NotFound
Users = pymongo.Connection("localhost", 27017)["mydb"]["users"]
class User(Resource):
def GET(self, request, username):
spec = {
"_id": username,
"_meta.active": True
}
# this is a simple call to pymongo - really, do
# we need anything else?
doc = Users.find_one(spec)
if not doc:
return NotFound(username)
payload, mimetype = representation(doc, request.accept)
return Response(payload, mimetype=mimetype, status=200)
def PUT(self, request, username):
spec = {
"_id": username,
"_meta.active": True
}
operation = {
"$set": request.json,
}
# this call to pymongo will return the updated document (implies safe=True)
doc = Users.update(spec, operation, new=True)
if not doc:
return NotFound(username)
payload, mimetype = representation(doc, request.accept)
return Response(payload, mimetype=mimetype, status=200)
Resource
基类看起来像
class Resource(object):
def GET(self, request, **kwargs):
return NotImplemented()
def HEAD(self, request, **kwargs):
return NotImplemented()
def POST(self, request, **kwargs):
return NotImplemented()
def DELETE(self, request, **kwargs):
return NotImplemented()
def PUT(self, request, **kwargs):
return NotImplemented()
def __call__(self, request, **kwargs):
handler = getattr(self, request.method)
return handler(request, **kwargs)
请注意,我直接使用 WSGI
规范,并尽可能利用 Werkzeug
(顺便说一下,我认为 Flask
添加了不必要的Werkzeug
的复杂性)。
representation
函数获取请求的 Accept
header ,并生成合适的表示(例如,application/json
或 文本/html
)。实现起来并不难。它还添加了 Last-Modified
header 。
当然,您的输入需要经过清理,并且呈现的代码将无法正常工作(我的意思是作为示例,但不难理解我的观点)。
我再次尝试了所有方法,但这种架构使我的代码灵活、简单且可扩展。
关于python - MongoKit vs MongoEngine vs Flask-MongoAlchemy for Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9447629/