|
1 | | -#Copyright (c) Microsoft Corporation. All rights reserved. |
2 | | -#Licensed under the MIT License. |
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
3 | 3 |
|
4 | 4 | # -*- coding: utf-8 -*- |
5 | 5 |
|
6 | | -import http.client, urllib.parse, json |
| 6 | +import http.client |
| 7 | +import json |
| 8 | +import urllib.parse |
| 9 | +import os |
7 | 10 |
|
8 | | -# ********************************************** |
9 | | -# *** Update or verify the following values. *** |
10 | | -# ********************************************** |
| 11 | +''' |
| 12 | +This sample makes a call to the Bing News Search API with a text query and returns relevant news webpages. |
| 13 | +Documentation: https: // docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/ |
| 14 | +''' |
11 | 15 |
|
12 | | -# Add your Bing Search V7 subscription key to your environment variables. |
| 16 | +# Add your Bing Search V7 subscription key and endpoint to your environment variables. |
13 | 17 | subscriptionKey = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY'] |
14 | | - |
15 | | -# Add your Bing Search V7 endpoint to your environment variables. |
16 | 18 | host = os.environ['BING_SEARCH_V7_ENDPOINT'] |
| 19 | +host = host.replace('https://', '') |
17 | 20 | path = "/bing/v7.0/news/search" |
18 | 21 |
|
19 | 22 | term = "Microsoft" |
20 | 23 |
|
21 | | -def BingNewsSearch(search): |
22 | | - "Performs a Bing News search and returns the results." |
23 | | - |
24 | | - headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} |
25 | | - conn = http.client.HTTPSConnection(host) |
26 | | - query = urllib.parse.quote(search) |
27 | | - conn.request("GET", path + "?q=" + query, headers=headers) |
28 | | - response = conn.getresponse() |
29 | | - headers = [k + ": " + v for (k, v) in response.getheaders() |
30 | | - if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")] |
31 | | - return headers, response.read().decode("utf8") |
32 | | - |
| 24 | +# Construct the request. |
| 25 | +headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} |
| 26 | +conn = http.client.HTTPSConnection(host) |
| 27 | +query = urllib.parse.quote(term) |
33 | 28 | print('Searching news for: ', term) |
| 29 | +conn.request("GET", path + "?q=" + query, headers=headers) |
| 30 | +response = conn.getresponse() |
| 31 | +headers = [k + ": " + v for (k, v) in response.getheaders() |
| 32 | + if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")] |
34 | 33 |
|
35 | | -headers, result = BingNewsSearch(term) |
| 34 | +# Print search results. |
36 | 35 | print("\nRelevant HTTP Headers:\n") |
37 | 36 | print("\n".join(headers)) |
38 | 37 | print("\nJSON Response:\n") |
39 | | -print(json.dumps(json.loads(result), indent=4)) |
| 38 | +print(json.dumps(json.loads(response.read()), indent=4)) |
0 commit comments