diff --git a/python/Search/BingImageSearchv7.py b/python/Search/BingImageSearchv7.py index 191378d..645c5a0 100644 --- a/python/Search/BingImageSearchv7.py +++ b/python/Search/BingImageSearchv7.py @@ -1,46 +1,42 @@ -#Copyright (c) Microsoft Corporation. All rights reserved. -#Licensed under the MIT License. +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. # -*- coding: utf-8 -*- -import http.client, urllib.parse, json +import http.client +import urllib.parse +import json +import os +from pprint import pprint -# ********************************************** -# *** Update or verify the following values. *** -# ********************************************** +''' +This sample makes a call to the Bing Image Search API with a text query and returns relevant images with data. +Documentation: https: // docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/ +''' -# Add your Bing Search V7 subscription key to your environment variables. +# Add your Bing Search V7 subscription key and endpoint to your environment variables. subscriptionKey = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY'] - -# Add your Bing Search V7 endpoint to your environment variables. host = os.environ['BING_SEARCH_V7_ENDPOINT'] +host = host.replace('https://', '') path = "/bing/v7.0/images/search" -term = "puppies" - -def BingImageSearch(search): - "Performs a Bing image search and returns the results." - - headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} - conn = http.client.HTTPSConnection(host) - query = urllib.parse.quote(search) - conn.request("GET", path + "?q=" + query, headers=headers) - response = conn.getresponse() - headers = [k + ": " + v for (k, v) in response.getheaders() - if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")] - return headers, response.read().decode("utf8") - -if len(subscriptionKey) == 32: +# Query to search for +query = "puppies" - print('Searching images for: ', term) +# Construct a request +headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} +conn = http.client.HTTPSConnection(host) +query_search = urllib.parse.quote(query) +conn.request("GET", path + "?q=" + query_search, headers=headers) - headers, result = BingImageSearch(term) - print("\nRelevant HTTP Headers:\n") - print("\n".join(headers)) - print("\nJSON Response:\n") - print(json.dumps(json.loads(result), indent=4)) +# Print response +response = conn.getresponse() +headers = [k + ": " + v for (k, v) in response.getheaders() + if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")] -else: +print('Searching images for: ', query) - print("Invalid Bing Search API subscription key!") - print("Please paste yours into the source code.") +print("\nRelevant HTTP Headers:\n") +print("\n".join(headers)) +print("\nJSON Response:\n") +pprint(json.loads(response.read()))