首页 > 解决方案 > 如何使用 python 中的请求和时间模块向 API 端点发送随机获取请求

问题描述

如何使用 python 中的请求和时间模块向 API 端点发送随机获取请求

标签: pythondjangoautomationrequest

解决方案


如果您只想要一个如何执行请求的示例,这里是一个从 api 获取产品列表的请求。

# import the Requests library 
import requests
# define the base URL for the API 
base_url = 'http://127.0.0.1:8000/api/' 
# random example of a get a list of products,(put your specific endpoint)
r = requests.get(f'{base_url}products/')
# json() method of the response object to decode the JSON data returned by the API
products = r.json()
products_list = ', '.join([product['name'] for product in products])
# print products names
print(f'Available products: {products_list}')

或者您可以在函数或类中使用“产品”作为上下文


推荐阅读