Advertisement
Guest User

helpers.py

a guest
Jan 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. import feedparser
  2. import urllib.parse
  3.  
  4.  
  5. def lookup(geo):
  6.     """Look up articles for geo"""
  7.  
  8.     # Check cache
  9.     try:
  10.         if geo in lookup.cache:
  11.             return lookup.cache[geo]
  12.     except AttributeError:
  13.         lookup.cache = {}
  14.  
  15.     # Replace special characters
  16.     escaped = urllib.parse.quote(geo, safe="")
  17.  
  18.     # Get feed from Google
  19.     feed = feedparser.parse(f"https://news.google.com/news/rss/local/section/geo/{escaped}")
  20.  
  21.     # If no items in feed, get feed from Onion
  22.     if not feed["items"]:
  23.         feed = feedparser.parse("http://www.theonion.com/feeds/rss")
  24.  
  25.     # Cache results
  26.     lookup.cache[geo] = [{"link": item["link"], "title": item["title"]} for item in feed["items"]]
  27.  
  28.     # Return results
  29.     return lookup.cache[geo]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement