MongoKit vs MongoEngine vs Flas的Flask MongoAlchemy

2024-09-20 22:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有人对MongoKit,MongoEngine或烧瓶MongoAlchemy有经验吗?

你喜欢哪一个?积极或消极的经历?。对于一个酒瓶新手来说,选择太多了。


Tags: 烧瓶经验经历mongoengine消极新手mongoalchemy酒瓶
1条回答
网友
1楼 · 发布于 2024-09-20 22:23:52

我花了很多时间来评估流行的MongoDB Python ORMs。这是一个详尽的练习,因为我真的很想选一个。

我的结论是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(顺便说一下,我认为FlaskWerkzeug增加了不必要的复杂度)。

函数representation接受请求的Accept头,并生成适当的表示(例如,application/json,或text/html)。实施起来并不难。它还添加了Last-Modified头。

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

再一次,我尝试了所有的方法,但是这个架构使我的代码变得灵活、简单和可扩展。

相关问题 更多 >

    热门问题