我是使用 API 的新手。对于某些背景,有问题的 API 采用以下参数来检索响应对象:
- API_ID- 用于访问 API 端点的 ID 凭据。
- API_KEY- 访问 API 端点的密钥
- 位置 - 十进制纬度/经度坐标列表(最多 5 个)
- 开始 - 观察期开始的 Unix 时间戳
- 结束 - 观察期结束的 Unix 时间戳
我要做的是创建一个类对象,其中包含检索数据所需的所有信息。这个类对象是这样写的:
class API_call:
def __init__(self, app_id, app_key, location, start, end):
self.app_id = app_id
self.app_key = app_key
self.location = location
self.start = start
self.end = end
当我创建 API_call 对象时,我将 API ID ( api_id) 和 API Key ( api_key) 存储为字符串和函数,以创建用户生成的坐标列表 ( enter_locations()) 和开始/结束时间作为 unix 时间戳 ( start_datetime_to_unix()/ end_datetime_to_unix())。
API_call_object = API_call(‘api_id’,’api_key',
enter_location(),
start_datetime_to_unix(),
end_datetime_to_unix()
)
这一步通常没有问题,除非我在提示期间输入了错误,但很快就解决了。创建对象后,我尝试将不同的信息传递到requests.get( )其中并将其保存为变量。
response_object = requests.get(f’{URL_OF_THE_API_ENDPOINT}?app_id={API_call_object.app_id}&app_key={API_call_object.app_key}&location={API_call_object.location}&start={API_call_object.start}&end={API_call_object.end}').json()
我已经解决了这个问题,足以知道如果我通过了除API_call_object.location参数之外的所有内容,则脚本可以正常工作。这个问题与如何location解释论点有关。当我只输入一个坐标时,一切都通过了,我得到了我请求的响应对象。但是,如果我输入多个坐标并将它们作为元组列表返回(例如 [(40.66,-87.32),(42.54,-85.78)])然后传入requests.get( ),我会收到此错误:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
将输出转换enter_locations()为字符串没有帮助。也不会尝试传递仅返回静态列表的不同函数的输出。我将包含该enter_location()函数的脚本,以防它与解决此问题有关。我承认这可能不是最好的方法,但它适用于我想做的事情。
def enter_location():
location_list = []
count = 1
Lat1 = float(input("Enter your first LAT coordinate ")
)
Lon1 = float(input("Enter you first LON coordinate ")
)
Loc1 = (Lat1, Lon1)
location_list.append(Loc1)
add_more = input("Enter more coordinates? Y/N ")
if add_more == 'Y':
Lat2 = float(input("Enter your second LAT coordinate ")
)
Lon2 = float(input("Enter you second LON coordinate ")
)
Loc2 = (Lat2, Lon2)
location_list.append(Loc2)
add_more = input("Enter more coordinates? Y/N ")
if add_more == 'Y':
Lat3 = float(input("Enter your third LAT coordinate ")
)
Lon3 = float(input("Enter you third LON coordinate ")
)
Loc3 = (Lat3, Lon3)
location_list.append(Loc3)
add_more = input("Enter more coordinates? Y/N ")
if add_more == 'Y':
Lat4 = float(input("Enter your fourth LAT coordinate ")
)
Lon4 = float(input("Enter you fourth LON coordinate ")
)
Loc4 = (Lat4, Lon4)
location_list.append(Loc4)
add_more = input("Enter more coordinates? Y/N ")
if add_more == 'Y':
Lat5 = float(input("Enter your third LAT coordinate ")
)
Lon5 = float(input("Enter you third LON coordinate ")
)
Loc5 = (Lat5, Lon5)
location_list.append(Loc5)
else:
pass
else:
pass
else:
pass
else:
pass
return location_list