Friendly King
Friendly King

Reputation: 2476

Using a generator in Pyramid view called by Ajax

I would like to lazily load items to my HTML. Each item is computationally laborious, so I only would like to load and process the bare minimum necessary. I thought a generator would be a good solution to this.

In a nutshell, I have something like

@view_config(renderer='json', xhr=True, route_name='load_more_posts')
def load_more_posts(self):  
    items = Render.get_items(5)
    return items

Where Render is just my class name, and get_items is a method which calls my generator's next() method 5 times, each time retrieving a new item and adding to a list. Now I have a list items and I want to simply output it via JSON.

How can I make this work? Every time I call this view with my AJAX call, the generator is 're-instantiated' and I only ever get the first 5 items. Is there a way to have this generator persist between AJAX calls so subsequent calls to it will progress through it and finally exhaust it?

Thank you.

Upvotes: 0

Views: 152

Answers (1)

Antoine Leclair
Antoine Leclair

Reputation: 18050

Persisting your generator is not a good idea. It would bring statefulness to your HTTP app.

Instead, use paging.

/posts?page=2

Upvotes: 3

Related Questions