Skip to content

Commit 11fabc6

Browse files
authored
Updated library
1 parent a403902 commit 11fabc6

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

python/Search/BingImageSearchv7.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@
33

44
# -*- coding: utf-8 -*-
55

6-
import http.client
7-
import urllib.parse
86
import json
97
import os
108
from pprint import pprint
9+
import requests
1110

1211
'''
1312
This sample makes a call to the Bing Image Search API with a text query and returns relevant images with data.
@@ -16,27 +15,25 @@
1615

1716
# Add your Bing Search V7 subscription key and endpoint to your environment variables.
1817
subscriptionKey = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY']
19-
host = os.environ['BING_SEARCH_V7_ENDPOINT']
20-
host = host.replace('https://', '')
21-
path = "/bing/v7.0/images/search"
18+
endpoint = os.environ['BING_SEARCH_V7_ENDPOINT'] + "/bing/v7.0/images/search"
2219

2320
# Query to search for
2421
query = "puppies"
2522

2623
# Construct a request
24+
mkt = 'en-US'
25+
params = {'q': query, 'mkt': mkt}
2726
headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
28-
conn = http.client.HTTPSConnection(host)
29-
query_search = urllib.parse.quote(query)
30-
conn.request("GET", path + "?q=" + query_search, headers=headers)
3127

32-
# Print response
33-
response = conn.getresponse()
34-
headers = [k + ": " + v for (k, v) in response.getheaders()
35-
if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")]
28+
# Call the API
29+
try:
30+
response = requests.get(endpoint, headers=headers, params=params)
31+
response.raise_for_status()
3632

37-
print('Searching images for: ', query)
33+
print("\nHeaders:\n")
34+
print(response.headers)
3835

39-
print("\nRelevant HTTP Headers:\n")
40-
print("\n".join(headers))
41-
print("\nJSON Response:\n")
42-
pprint(json.loads(response.read()))
36+
print("\nJSON Response:\n")
37+
pprint(response.json())
38+
except Exception as ex:
39+
raise ex

0 commit comments

Comments
 (0)