我已经可以使用 Python 在名为 api.py 的 Django 文件夹中打印搜索结果中的数据。但是现在,我如何将这些数据移动到 React 中来显示它?谁能帮我提供一个详细的方法来做到这一点。非常感谢!
我还将 Bing API 密钥存储在 .env 文件中,当前与 api.py 文件处于同一文件级别。
必应网络搜索 API: https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/reference/endpoints
代码:在api.py文件中
`from pprint import pprint
import requests
from decouple import config
subscription_key = config('subscription_key', default='')
search_url = "https://api.bing.microsoft.com/v7.0/search"
search_term = 'iphone 13'
headers = {"Ocp-Apim-Subscription-Key": subscription_key}
params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()
pages = search_results\['webPages'\]
results = pages\['value'\]
pprint(results\[0\])`
我尝试浏览 stackoverflow 和整个互联网,没有发现有人真正使用这个 API..
为什么不在 Django 应用程序中创建 GET api 并将整个逻辑放在视图 DRF 视图中。例如,将此端点映射到您的视图上
yourapp/search
。 最后从你的 React 应用程序中调用这个 api