Source

newsmeme / posts.py


from mongoengine import *
from mongoengine.queryset import QuerySet, DoesNotExist, queryset_manager
from pymongo.objectid import ObjectId

from flask import abort

connect("newsmeme-dev")

class Paginator(object):

    def paginate(self, queryset):
        return []


"""
page_obj = paginate(Post.objects.public(),
                    page,
                    Post.PER_PAGE)

post = get_or_404(Post.objects.public(), id=1)

"""

class SomeQuerySet(QuerySet):

    def get_or_404(self, **kwargs):
        try:
            return self.get(**kwargs)
        except DoesNotExist:
            abort(404)

    def paginate(self, page, page_size):
        return []

    def restricted(self):
        return self.filter(access=Post.PUBLIC)

    def popular(self):
        return self.filter(access=Post.PUBLIC)

class Post(Document):

    PUBLIC = 100
    PRIVATE = 200

    title = StringField()
    description = StringField()
    access = IntField(default=PUBLIC)

    meta  = {'queryset_class' : SomeQuerySet}

    @queryset_manager
    def public(cls, queryset):
        return queryset.filter(access=cls.PUBLIC)

post = Post.objects.restricted().get_or_404(id=ObjectId("4d0642b42f54ae12b0000000"))
print post.title

#post = Post.objects.get_or_404(id=ObjectId("4d0642b42f54ae12b0000001"))
post = Post.objects.popular().restricted().with_id("4d0642b42f54ae12b0000000")
print post.title