Skip to content

Instantly share code, notes, and snippets.

@Sealjay
Last active February 10, 2021 01:36
Show Gist options
  • Save Sealjay/e8a708866732ccd479a9cf069cfc84a3 to your computer and use it in GitHub Desktop.
Save Sealjay/e8a708866732ccd479a9cf069cfc84a3 to your computer and use it in GitHub Desktop.
bingnews-cli - request example
import os
import textwrap
import requests
import pyshorteners
from tabulate import tabulate
def clean_trending_article_dictionary(article_dictionary):
"""Take a dictionary for a trending article, and tweak the output."""
source = article_dictionary["image"]["provider"][0]
article_dictionary["title"] = article_dictionary["name"]
article_dictionary["url"] = article_dictionary["webSearchUrl"]
article_dictionary[
"description"
] = f"Provided by {source['name']}, an {source['_type']}."
return article_dictionary
def clean_bing_article_list(bing_article_list):
"""Take a list of articles, and clean the outputs."""
cleaned_list = []
shortener = pyshorteners.Shortener()
for item in bing_article_list:
if "name" in item and "webSearchUrl" in item:
item = clean_trending_article_dictionary(item)
new_dictionary = {
"Title": "\n".join(textwrap.wrap(item["name"], width=40)),
"Description": "\n".join(textwrap.wrap(item["description"], width=60)),
"URL": shortener.qpsru.short(item["url"]),
}
cleaned_list.append(new_dictionary)
return cleaned_list
def print_bing_results(bing_response_json):
"""Print out the results of the Bing News API output."""
assert "value" in bing_response_json
articles = bing_response_json["value"]
cleaned_articles = clean_bing_article_list(articles)
click.secho(
tabulate(
cleaned_articles,
headers="keys",
tablefmt="grid",
colalign=["left", "left", "left"],
)
)
if "totalEstimatedMatches" in bing_response_json:
click.secho(f"{bing_response_json['totalEstimatedMatches']} estimated matches.")
def search_and_output_bing(query_string="", params=None):
"""Take the different variation of bing queries, and call the API."""
if params is None:
params = {}
subscription_key = os.getenv("BING_SEARCH_KEY")
assert subscription_key is not None
bing_search_endpoint = os.getenv("BING_SEARCH_ENDPOINT")
assert bing_search_endpoint is not None
search_url = f"{bing_search_endpoint}v7.0/news{query_string}"
headers = {"Ocp-Apim-Subscription-Key": subscription_key}
response = requests.get(search_url, headers=headers, params=params)
try:
response.raise_for_status()
print_bing_results(response.json())
except requests.exceptions.HTTPError as error:
click.secho(f"Error: {str(error)}", fg="red")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment