MongoKit vs MongoEngine vs Flask-MongoAlchemy for Flask

osc*_*age 72 python sqlalchemy mongodb flask

任何人都有使用MongoKit,MongoEngine或Flask-MongoAlchemy for Flask的经验吗?

你更倾向哪个?积极或消极的经历?Flask-Newbie的选项太多了.

Esc*_*alo 83

我花了很多时间来评估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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

请注意,我WSGI直接使用规范,并Werkzeug尽可能利用(顺便说一下,我认为这Flask会增加不必要的复杂性Werkzeug).

该函数representation接收请求的Accept标头,并生成合适的表示(例如application/json,或text/html).实施并不困难.它还添加了Last-Modified标题.

当然,您的输入需要进行清理,并且所显示的代码不起作用(我的意思是它作为一个例子,但我不难理解我的观点).

我再次尝试了一切,但这种架构使我的代码变得灵活,简单和可扩展.

  • +1.你不需要在Mongo之上使用ORM.直接使用Pymongo将为您提供完全的自由. (9认同)
  • @tim我不知道我三年前写这本书时在想什么,但是现在我的建议是您使用工具,因为您知道它可以解决您要解决的问题。在大多数情况下,可靠的关系数据库(例如Postgres)将解决您所有的数据持久性,聚合和分析问题,同时以软件尚未实现的增长方式保护您的数据。 (2认同)