def obama_reps(): """ Ongoing list of Incumbent Republicans In Districts Barack Obama Won In 2012 """ from models import Race races = Race.select().where(Race.obama_gop == True).order_by(Race.state_postal, Race.seat_number) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) won = [race for race in races if race.is_called() and not race.is_runoff() and not race.party_changed()] lost = [race for race in races if race.is_called() and not race.is_runoff() and race.party_changed()] not_called = [race for race in races if not race.is_called() or race.is_runoff()] context['races_won'] = columnize_card(won) context['races_lost'] = columnize_card(lost) context['races_not_called'] = columnize_card(not_called) context['races_won_count'] = len(won) context['races_lost_count'] = len(lost) context['races_not_called_count'] = len(not_called) context['races_count'] = races.count() return render_template('slides/obama-reps.html', **context)
def _post(slug): """ Renders a post without the tumblr wrapper. """ post_path = '%s/%s' % (app_config.POST_PATH, slug) context = make_context() context['slug'] = slug context['COPY'] = copytext.Copy(filename='data/%s.xlsx' % slug) context['JS'] = JavascriptIncluder(asset_depth=2, static_path=post_path) context['CSS'] = CSSIncluder(asset_depth=2, static_path=post_path) try: post_config = imp.load_source('post_config', '%s/post_config.py' % post_path) context.update(post_config.__dict__) except IOError: pass if os.path.exists('%s/featured.json' % post_path): with open('%s/featured.json' % post_path) as f: context['featured'] = json.load(f) with open('%s/templates/index.html' % post_path) as f: template = f.read().decode('utf-8') return make_response(render_template_string(template, **context))
def balance_of_power(): """ Serve up the balance of power graph """ from models import Race house_races = Race.select().where(Race.office_name == 'U.S. House').order_by(Race.state_postal) senate_races = Race.select().where(Race.office_name == 'U.S. Senate').order_by(Race.state_postal) senate_updated = get_last_updated(senate_races) house_updated = get_last_updated(house_races) if senate_updated > house_updated: last_updated = senate_updated else: last_updated = house_updated context = make_context(timestamp=last_updated) context['page_title'] = 'Balance of Power' context['page_class'] = 'balance-of-power' context['house_bop'] = calculate_bop(house_races, HOUSE_INITIAL_BOP) context['senate_bop'] = calculate_bop(senate_races, SENATE_INITIAL_BOP) context['house_not_called'] = calculate_seats_left(house_races) context['senate_not_called'] = calculate_seats_left(senate_races) return render_template('slides/balance-of-power.html', **context)
def _episode_detail(episode_code): context = make_context() context['episode'] = Episode.get(Episode.code == episode_code) context['jokes'] = {} context['joke_count'] = 0 for joke in EpisodeJoke.select().where( EpisodeJoke.episode == context['episode']): group = joke.joke.primary_character if group not in app_config.PRIMARY_CHARACTER_LIST: group = 'Miscellaneous' if group not in context['jokes']: context['jokes'][group] = [] context['jokes'][group].append(joke) context['joke_count'] += 1 context['seasons'] = _all_seasons() context['group_order'] = [ g for g in app_config.PRIMARY_CHARACTER_LIST if g in context['jokes'] ] try: context['next'] = Episode.get(number=context['episode'].number + 1) except Episode.DoesNotExist: context['next'] = None try: context['prev'] = Episode.get(number=context['episode'].number - 1) except Episode.DoesNotExist: context['prev'] = None return render_template('episode_detail.html', **context)
def index(): import feedparser noticias_tumblr = "http://blog.periodismodedatos.org/rss" feed = feedparser.parse(noticias_tumblr) return render_template("index.html", menu="MPDI", feed=feed, **make_context())
def index(): """ Example view demonstrating rendering a simple HTML page. """ context = make_context() context['characters'] = get_character_slugs(); return make_response(render_template('index.html', **context))
def index(): """ Render the admin index. """ context = make_context() return render_template('index.html', **context)
def _stack(): """ Administer a stack of slides. """ context = make_context(asset_depth=1) sequence = SlideSequence.select() sequence_dicts = sequence.dicts() time = 0 for slide in sequence: time += slide.slide.time_on_screen for slide_dict in sequence_dicts: for slide in sequence: if slide.slide.slug == slide_dict['slide']: slide_dict['name'] = slide.slide.name slide_dict['time_on_screen'] = slide.slide.time_on_screen if slide_dict['slide'].startswith('tumblr'): slide_dict['news_item'] = True context.update({ 'sequence': sequence_dicts, 'slides': Slide.select().dicts(), 'graphics': Slide.select().where(fn.Lower(fn.Substr(Slide.slug, 1, 6)) != 'tumblr').order_by(Slide.slug).dicts(), 'news': Slide.select().where(fn.Lower(fn.Substr(Slide.slug, 1, 6)) == 'tumblr').order_by(Slide.slug.desc()).dicts(), 'time': time, }) return render_template('admin/stack.html', **context)
def index(): """ Example view demonstrating rendering a simple HTML page. """ incidents_with_age = Incident.select().where(Incident.age > 0).order_by( Incident.age.asc()) incidents_without_age = Incident.select().where( Incident.age >> None).order_by(Incident.age.asc()) incidents = list(incidents_with_age) + list(incidents_without_age) states = [ i.state for i in Incident.select(Incident.state).distinct().order_by( Incident.state) ] def slug(incident): uniq = incident.name or 'unknown' if (incident.postofficename): uniq += '-' + incident.postofficename uniq += '-' + incident.state return uniq.lower().replace(' ', '-').replace('.', '').replace('--', '-') return render_template('index.html', incidents=incidents, states=states, slug=slug, **make_context())
def _episode_detail(episode_code): context = make_context() context['episode'] = Episode.get(Episode.code == episode_code) context['jokes'] = {} context['joke_count'] = 0 for joke in EpisodeJoke.select().where(EpisodeJoke.episode == context['episode']): group = joke.joke.primary_character if group not in app_config.PRIMARY_CHARACTER_LIST: group = 'Miscellaneous' if group not in context['jokes']: context['jokes'][group] = [] context['jokes'][group].append(joke) context['joke_count'] += 1 context['seasons'] = _all_seasons() context['group_order'] = [g for g in app_config.PRIMARY_CHARACTER_LIST if g in context['jokes']] try: context['next'] = Episode.get(number=context['episode'].number + 1) except Episode.DoesNotExist: context['next'] = None try: context['prev'] = Episode.get(number=context['episode'].number - 1) except Episode.DoesNotExist: context['prev'] = None return render_template('episode_detail.html', **context)
def _story(slug): context = make_context() context['story'] = list(context['COPY'][slug]) context['slug'] = slug return render_template('story.html', **context)
def index(): """ Example view rendering a simple page. """ context = make_context(asset_depth=1) return make_response(render_template('index.html', **context))
def preview(path): context = make_context() path_parts = path.split('/') slug = path_parts[0] args = path_parts[1:] context['content'] = app.view_functions[slug](*args) return make_response(render_template('index.html', **context))
def delegates(party): """ Render the results card """ context = make_context() ap_party = utils.PARTY_MAPPING[party]['AP'] candidates = models.CandidateDelegates.select().where( models.CandidateDelegates.party == ap_party, models.CandidateDelegates.level == 'nation', models.CandidateDelegates.last << DELEGATE_WHITELIST[party], models.CandidateDelegates.delegates_count > 0 ).order_by( -models.CandidateDelegates.delegates_count, models.CandidateDelegates.last ) context['last_updated'] = utils.get_delegates_updated_time() context['candidates'] = candidates context['needed'] = list(candidates)[0].party_need context['party'] = ap_party context['party_class'] = utils.PARTY_MAPPING[party]['class'] context['party_long'] = utils.PARTY_MAPPING[party]['adverb'] context['slug'] = 'delegates-%s' % party context['template'] = 'delegates' context['route'] = '/delegates/%s/' % party context['refresh_rate'] = app_config.LOAD_DELEGATES_INTERVAL return render_template('cards/delegates.html', **context)
def rematches(): """ List of elections with candidates who have faced off before """ context = make_context() return render_template('slides/rematches.html', **context)
def index(): """ Example view rendering a simple page. """ context = make_context(asset_depth=1) return render_template("index.html", **context)
def methodology(): """ Methodology explainer page. """ context = make_context() return render_template('methodology.html', **context)
def index(): """ Example view demonstrating rendering a simple HTML page. """ context = make_context() # Nav needs to be a list of lists. # The inner list should only have four objects max. # Because of reasons. context['nav'] = [] contents = list(context['COPY']['content']) not_yet_four = [] for idx, row in enumerate(contents): row = dict(zip(row.__dict__['_columns'], row.__dict__['_row'])) row_title = row.get('data_panel', None) if row_title: if row_title not in ['_', 'introduction', 'data_panel', 'about']: not_yet_four.append(row) if len(not_yet_four) == 4: context['nav'].append(not_yet_four) not_yet_four = [] if (idx + 1) == len(contents): if len(not_yet_four) > 0: context['nav'].append(not_yet_four) return render_template('index.html', **context)
def sitemap(): """ Renders a sitemap. """ context = make_context() context['pages'] = [] now = datetime.date.today().isoformat() context['pages'].append(('/', now)) context['pages'].append(('/methodology/', now)) context['pages'].append(('/legislators/', now)) context['pages'].append(('/organizations/', now)) for legislator in Legislator.select(): context['pages'].append((url_for('_legislator', slug=legislator.slug), now)) for organization in Organization.select(): context['pages'].append((url_for('_organization', slug=organization.slug), now)) sitemap = render_template('sitemap.xml', **context) return (sitemap, 200, {'content-type': 'application/xml'})
def table(): """ the pym-child table """ context = make_context() return make_response(render_template('table.html', **context))
def _graphics_detail(slug): """ Renders a parent.html index with child.html embedded as iframe. """ from flask import request graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) # NOTE: Parent must load pym.js from same source as child to prevent # version conflicts! context = make_context(asset_depth=2, root_path=graphic_path) context['slug'] = slug context['type'] = 'graphics' # From previous commit context['var_name'] = slug.replace('-', '_') template = 'parent.html' if not os.path.exists('%s/%s/js/lib/pym.js' % (app_config.GRAPHICS_PATH, slug)): template = 'parent_old.html' try: graphic_config = load_graphic_config(graphic_path) context.update(graphic_config.__dict__) if hasattr(graphic_config, 'COPY_GOOGLE_DOC_KEY') and graphic_config.COPY_GOOGLE_DOC_KEY: copy_path = '%s/%s.xlsx' % (graphic_path, slug) if request.args.get('refresh'): oauth.get_document(graphic_config.COPY_GOOGLE_DOC_KEY, copy_path) context['COPY'] = copytext.Copy(filename=copy_path) except IOError: pass return make_response(render_template(template, **context))
def embedding(): """ instructions on embedding this item """ context = make_context() return make_response(render_template('embedding.html', **context))
def _templates_detail(slug): """ Renders a parent.html index with child.html embedded as iframe. """ from flask import request template_path = '%s/%s' % (app_config.TEMPLATES_PATH, slug) base_template_path = '%s/%s' % (app_config.TEMPLATES_PATH, '_base') # NOTE: Parent must load pym.js from same source as child to prevent version conflicts! context = make_context(asset_depth=2, root_path=template_path) context['slug'] = slug try: graphic_config = load_graphic_config(template_path, [base_template_path]) context.update(graphic_config.__dict__) if hasattr(graphic_config, 'COPY_GOOGLE_DOC_KEY') and graphic_config.COPY_GOOGLE_DOC_KEY: copy_path = '%s/%s.xlsx' % (template_path, slug) if request.args.get('refresh'): oauth.get_document(graphic_config.COPY_GOOGLE_DOC_KEY, copy_path) context['COPY'] = copytext.Copy(filename=copy_path) except IOError: pass return make_response(render_template('parent.html', **context))
def index(): """ The index page. """ # Set up standard page context. context = make_context() with open('data/featured.json') as f: context['featured'] = json.load(f) # Read the books JSON into the page. with open('www/static-data/books.json', 'rb') as readfile: context['books_js'] = readfile.read() books = json.loads(context['books_js']) books_text_only = books[:] books_text_only = sorted(books, key=_title_sorter) for book in books: if not book['text']: book['teaser'] = None else: book['teaser'] = _make_teaser(book) context['books'] = books context['books_text_only'] = books_text_only return render_template('index.html', **context)
def _graphics_child(slug): """ Renders a child.html for embedding. """ graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) # Fallback for legacy projects w/o child templates if not os.path.exists('%s/child_template.html' % graphic_path): with open('%s/child.html' % graphic_path) as f: contents = f.read() return contents context = make_context() context['slug'] = slug context['COPY'] = copytext.Copy(filename='data/%s.xlsx' % slug) try: graphic_config = imp.load_source('graphic_config', '%s/graphic_config.py' % graphic_path) context.update(graphic_config.__dict__) except IOError: pass with open('%s/child_template.html' % graphic_path) as f: template = f.read().decode('utf-8') return render_template_string(template, **context)
def search(): """ Search results page. """ context = make_context() return render_template('search.html', **context)
def add_search(): """ Pre-add search page """ context = make_context() return render_template('add_search.html', **context)
def house_freshmen(): """ Ongoing list of how representatives elected in 2012 are faring """ from models import Race races = Race.select().where(Race.freshmen == True)\ .order_by(Race.state_postal, Race.seat_number) timestamp = get_last_updated(races) context = make_context() won = [race for race in races if race.is_called() and not race.is_runoff() and not race.party_changed()] lost = [race for race in races if race.is_called() and not race.is_runoff() and race.party_changed()] not_called = [race for race in races if not race.is_called() or race.is_runoff()] context['races_won'] = columnize_card(won, 6) context['races_lost'] = columnize_card(lost, 6) context['races_not_called'] = columnize_card(not_called, 6) context['races_won_count'] = len(won) context['races_lost_count'] = len(lost) context['races_not_called_count'] = len(not_called) context['races_count'] = races.count() return render_template('slides/house-freshmen.html', **context)
def index(): context = make_context() with open('data/featured.json') as f: context['featured'] = json.load(f) return render_template('index.html', **context)
def house_big_board(page): """ House big board """ from models import Race all_races = Race.select().where(Race.office_name == 'U.S. House') all_featured_races = Race.select().where((Race.office_name == 'U.S. House') & (Race.featured_race == True)).order_by(Race.poll_closing_time, Race.state_postal, Race.seat_number) timestamp = get_last_updated(all_races) context = make_context(timestamp=timestamp) context['page_title'] = 'House' context['current_page'] = page context['page_class'] = 'house' if page == 2: featured_races = all_featured_races[HOUSE_PAGE_LIMIT:] else: featured_races = all_featured_races[:HOUSE_PAGE_LIMIT] context['poll_groups'] = columnize_races(featured_races) context['bop'] = calculate_bop(all_races, HOUSE_INITIAL_BOP) context['not_called'] = calculate_seats_left(all_races) context['seat_number'] = ".seat_number" return render_template('slides/race_results.html', **context)
def calls_admin(office): officename = SLUG_TO_OFFICENAME[office] # This value will be the same for all seats in a chamber, so pick # an arbitrary one chamber_call_override = models.RaceMeta.select( models.RaceMeta.chamber_call_override).join(models.Result).where( models.Result.officename == SLUG_TO_OFFICENAME[office]).scalar() results = app_utils.get_results(officename) if not results: # Occasionally, the database will erroneously return zero races # Handle this by signaling a server error # See https://github.com/nprapps/elections18-general/issues/24 return 'Server error; failed to fetch results from database', 500 context = make_context(asset_depth=1) context.update({ 'officename': officename, 'chamber_call_override': chamber_call_override, 'offices': SLUG_TO_OFFICENAME, 'races': results }) return make_response(render_template('calls.html', **context))
def romney_senate_dems(): """ Ongoing list of Democratically-held seats in states Mitt Romney Won In 2012 """ from models import Race races = Race.select().where( (Race.romney_dem == True) & (Race.office_name == 'U.S. Senate') ).order_by(Race.state_postal, Race.seat_number) timestamp = get_last_updated(races) context = make_context(timestamp=timestamp) won = [race for race in races if race.is_called() and not race.is_runoff() and not race.party_changed()] lost = [race for race in races if race.is_called() and not race.is_runoff() and race.party_changed()] not_called = [race for race in races if not race.is_called() or race.is_runoff()] context['races_won'] = columnize_card(won) context['races_lost'] = columnize_card(lost) context['races_not_called'] = columnize_card(not_called) context['races_won_count'] = len(won) context['races_lost_count'] = len(lost) context['races_not_called_count'] = len(not_called) context['races_count'] = races.count() return render_template('slides/romney-senate-dems.html', **context)
def index(): """ Example view demonstrating rendering a simple HTML page. """ context = make_context() # Nav needs to be a list of lists. # The inner list should only have four objects max. # Because of reasons. context["nav"] = [] contents = list(context["COPY"]["content"]) not_yet_four = [] for idx, row in enumerate(contents): row = dict(zip(row.__dict__["_columns"], row.__dict__["_row"])) row_title = row.get("data_panel", None) if row_title: if row_title not in ["_", "introduction", "data_panel", "about"]: not_yet_four.append(row) if len(not_yet_four) == 4: context["nav"].append(not_yet_four) not_yet_four = [] if (idx + 1) == len(contents): if len(not_yet_four) > 0: context["nav"].append(not_yet_four) with open("data/featured.json") as f: context["featured"] = json.load(f) return make_response(render_template("index.html", **context))
def promo(): """ Promo page. """ context = make_context() return render_template('promo.html', **context)
def index(): """ Example view demonstrating rendering a simple HTML page. """ context = make_context() # Nav needs to be a list of lists. # The inner list should only have four objects max. # Because of reasons. context['nav'] = [] contents = list(context['COPY']['content']) not_yet_four = [] for idx, row in enumerate(contents): row = dict(zip(row.__dict__['_columns'], row.__dict__['_row'])) row_title = row.get('data_panel', None) if row_title: if row_title not in ['_', 'introduction', 'data_panel', 'about']: not_yet_four.append(row) if len(not_yet_four) == 4: context['nav'].append(not_yet_four) not_yet_four = [] if (idx + 1) == len(contents): if len(not_yet_four) > 0: context['nav'].append(not_yet_four) with open('data/featured.json') as f: context['featured'] = json.load(f) return make_response(render_template('index.html', **context))
def delegates(party): """ Render the results card """ context = make_context() ap_party = utils.PARTY_MAPPING[party]['AP'] candidates = models.CandidateDelegates.select().where( models.CandidateDelegates.party == ap_party, models.CandidateDelegates.level == 'nation', models.CandidateDelegates.last << DELEGATE_WHITELIST[party], models.CandidateDelegates.delegates_count > 0).order_by( -models.CandidateDelegates.delegates_count, models.CandidateDelegates.last) context['last_updated'] = utils.get_delegates_updated_time() context['candidates'] = candidates context['needed'] = list(candidates)[0].party_need context['party'] = ap_party context['party_class'] = utils.PARTY_MAPPING[party]['class'] context['party_long'] = utils.PARTY_MAPPING[party]['adverb'] context['slug'] = 'delegates-%s' % party context['template'] = 'delegates' context['route'] = '/delegates/%s/' % party context['refresh_rate'] = app_config.LOAD_DELEGATES_INTERVAL return render_template('cards/delegates.html', **context)
def _graphics_detail(slug): """ Renders a parent.html index with child.html embedded as iframe. """ from flask import request graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug) # NOTE: Parent must load pym.js from same source as child to prevent version conflicts! context = make_context(asset_depth=2, root_path=graphic_path) context['slug'] = slug template = 'parent.html' try: graphic_config = load_graphic_config(graphic_path) context.update(graphic_config.__dict__) if hasattr(graphic_config, 'COPY_GOOGLE_DOC_KEY') and graphic_config.COPY_GOOGLE_DOC_KEY: copy_path = '%s/%s.xlsx' % (graphic_path, slug) if request.args.get('refresh'): oauth.get_document(graphic_config.COPY_GOOGLE_DOC_KEY, copy_path) context['COPY'] = copytext.Copy(filename=copy_path) except IOError: pass return make_response(render_template(template, **context))
def _graphics_list(): """ Renders a list of all graphics for local testing. """ context = make_context() context['graphics'] = [] context['templates'] = [] graphics = glob('%s/*' % app_config.GRAPHICS_PATH) for graphic in graphics: name = graphic.split('%s/' % app_config.GRAPHICS_PATH)[1].split('/child.html')[0] context['graphics'].append(name) context['graphics'].sort(); context['graphics_count'] = len(context['graphics']) templates = glob('%s/*' % app_config.TEMPLATES_PATH) for template in templates: name = template.split('%s/' % app_config.TEMPLATES_PATH)[1] if name.startswith('_'): continue context['templates'].append(name) context['templates'].sort() context['templates_count'] = len(context['templates']) return make_response(render_template('index.html', **context))
def _word(slug): context = make_context() data = {} for file in glob('data/text/counts/*.json'): with open(file) as f: transcript_data = json.load(f) date = file.split('/')[3].split('.')[0] data[date] = {} reporter_words = transcript_data['reporters']['words'] reporter_count = transcript_data['reporters']['count'] secretary_words = transcript_data['secretary']['words'] secretary_count = transcript_data['secretary']['count'] data[date]['reporter_count'] = reporter_count data[date]['secretary_count'] = secretary_count for word in reporter_words: for k, v in word.iteritems(): if k == slug: data[date]['reporter'] = v break for word in secretary_words: for k, v in word.iteritems(): if k == slug: data[date]['secretary'] = v break context['data'] = data return make_response(render_template('word.html', **context))
def index(): """ Example view demonstrating rendering a simple HTML page. """ context = make_context() return make_response(render_template('index.html', **context))
def share(slug): featured_book = None context = make_context() with open('www/static-data/books.json', 'rb') as f: books = json.load(f) for book in books: if book.get('slug') == slug: featured_book = book break if not featured_book: return 404 featured_book['thumb'] = "%sassets/cover/%s.jpg" % (context['SHARE_URL'], featured_book['slug']) try: book_image = Image.open('www/assets/cover/%s.jpg' % featured_book['slug']) width, height = book_image.size context['thumb_width'] = width context['thumb_height'] = height except IOError: context['thumb_width'] = None context['thumb_height'] = None context['twitter_handle'] = 'nprbooks' context['book'] = featured_book return make_response(render_template('share.html', **context))
def tag_share(slug): featured_tag = None context = make_context() tags = context['COPY']['tags'] for tag in tags: if tag['key'] == slug: featured_tag = tag break if not featured_tag: return 404 context['tag_thumb'] = "%sassets/tag/%s.jpg" % (context['SHARE_URL'], featured_tag['img']) try: book_image = Image.open('www/assets/tag/%s.jpg' % featured_tag['img']) width, height = book_image.size context['thumb_width'] = width context['thumb_height'] = height except IOError: context['thumb_width'] = None context['thumb_height'] = None context['twitter_handle'] = 'nprbooks' context['tag'] = featured_tag return make_response(render_template('tag_share.html', **context))
def _graphics_list(): """ Renders a list of all graphics for local testing. """ context = make_context() context['graphics'] = [] context['templates'] = [] graphics = glob('%s/*' % app_config.GRAPHICS_PATH) for graphic in graphics: name = graphic.split( '%s/' % app_config.GRAPHICS_PATH)[1].split('/child.html')[0] context['graphics'].append(name) context['graphics_count'] = len(context['graphics']) templates = glob('%s/*' % app_config.TEMPLATES_PATH) for template in templates: name = template.split('%s/' % app_config.TEMPLATES_PATH)[1] if name.startswith('_'): continue context['templates'].append(name) context['templates_count'] = len(context['templates']) return make_response(render_template('index.html', **context))