Question

I want to display the number of times an entity has been viewed directly on its template. For example, given this Book ndb.Model:

class Book(ndb.Model):
    title = ndb.StringProperty()
    view_count = ndb.IntegerProperty(default = 0)

It is handled by this:

class BookPage(MainHandler):
    def get(self, book_id):
        book = Book.get_by_id(int(book_id))
        self.render(book-page.html, book = book)

And here is the book-page.html:

<h2>{{book.title}} | {{book.view_count}}</h2>

One method is that we can set view_count = view_count + 1, and then book.put(), but this will involve a huge number of db writes.

There must be a better way.

Was it helpful?

Solution

Counter information is persistent, you don't have another option than writing it to datastore.

For a more efficient and fast implementation i would invite you to check out Sharding counters

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top