def process_stories(clusters): """ Takes clusters of node uuids and builds, modifies, and deletes stories out of them. `clusters` comes in as a list of lists, where sublists' members are article node ids. e.g:: [[1,2,3,4,5],[6,7,8,9]] """ story_map = {} existing = {} # Yikes this might be too much # TODO Should probably preserve existing story node id composition separately. for s in Story.query.all(): story_map[s.id] = s existing[s.id] = [e.id for e in s.events] # Figure out which stories to update, delete, and create. to_update, to_create, to_delete, unchanged = triage(existing, clusters) for e_ids in to_create: events = Event.query.filter(Event.id.in_(e_ids)).order_by(Event.created_at.desc()).all() story = Story(events) story.created_at = events[0].created_at story.updated_at = events[-1].created_at # TODO need a better way of coming up with a story title. # Perhaps the easiest way if stories just don't have titles and are just groupings of events. # For now, just using the latest event title and image. story.title = events[0].title story.image = events[0].image db.session.add(story) for s_id, e_ids in to_update.items(): s = story_map[s_id] events = Event.query.filter(Event.id.in_(e_ids)).order_by(Event.created_at.desc()).all() s.members = events s.title = events[0].title s.image = events[0].image s.update() for s_id in to_delete: db.session.delete(story_map[s_id]) db.session.commit() # Delete any stories that no longer have events. # http://stackoverflow.com/a/7954618/1097920 Story.query.filter(~Story.members.any()).delete(synchronize_session='fetch')
def _create_dated_story(self): datetime_A = datetime.utcnow() - timedelta(days=1) datetime_B = datetime.utcnow() - timedelta(days=5) article_a = fac.article(title='The Illiad', text='The Illiad has Argos in it.') event_a = Event([article_a]) event_a.created_at = datetime_A article_b = fac.article(title='The Illiad', text='The Illiad has Argos in it.') event_b = Event([article_b]) event_b.created_at = datetime_B article_c = fac.article(title='The Illiad', text='The Illiad has Argos in it.') event_c = Event([article_c]) event_c.created_at = datetime_A story = Story([event_a, event_b, event_c]) self.db.session.add(story) self.db.session.commit() return story, datetime_A, datetime_B