bing.py 1.13 KB
Newer Older
dengjb's avatar
dengjb committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Bing Search
"""
import os

import requests
from backend.apis.api import API

BING_API_KEY = os.getenv('BING_API_KEY')


class BingSearchAPI(API):
    def __init__(self):
        self.url = "https://api.bing.microsoft.com/v7.0/search"

    def search(self, query, freshness=None):
        """
        Search with bing

        References: https://docs.microsoft.com/en-us/bing/search-apis/bing-web-search/overview
        """
        response = requests.get(
            url=self.url,
            headers={"Ocp-Apim-Subscription-Key": BING_API_KEY},
            params={
                "q": query,
                "mkt": 'zh-CN',
                "freshness": freshness,
            },
            timeout=10,
        )
        try:
            json_content = response.json()
            contexts = json_content['webPages']['value'][:4]
            search_res = [{
                "url": item['url'],
                "title": item['name'],
                "snippet": item['snippet']
            } for item in contexts]
            return search_res
        except Exception as e:
            print(f"Searching failed, caused by {e}")
            return []