我该怎么做才能只需要引用一次 api 密钥?

How do I make it so I only need my api key referenced once?

我正在自学如何使用 python 和 django 访问 google 地点 api 以在附近搜索不同类型的健身房。

我只被教导如何使用 python 和 django 以及您在本地构建的数据库。

我为他们正在执行的四个不同搜索写了一个完整的 Get 请求。我查找了示例,但 none 似乎对我有用。

allgyms = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.9208,-77.036&radius=2500&type=gym&key=AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg')
all_text = allgyms.text
alljson = json.loads(all_text)

healthclubs = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.9208,-77.036&radius=2500&type=gym&keyword=healthclub&key=AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg')
health_text = healthclubs.text
healthjson = json.loads(health_text)

crossfit = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=38.9208,-77.036&radius=2500&type=gym&keyword=crossfit&key=AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg')
cross_text = crossfit.text
crossjson = json.loads(cross_text)

我真的很想知道如何在更改关键字时仅引用一次 api 键。

试试这个以获得更好的可读性和更好的可重用性

BASE_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
LOCATION = '38.9208,-77.036'
RADIUS = '2500'
TYPE = 'gym'
API_KEY = 'AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg'
KEYWORDS = ''

allgyms = requests.get(BASE_URL+'location='+LOCATION+'&radius='+RADIUS+'&type='+TYPE+'&key='+API_KEY) all_text = allgyms.text 
alljson = json.loads(all_text)

KEYWORDS = 'healthclub'
healthclubs = requests.get(BASE_URL+'location='+LOCATION+'&radius='+RADIUS+'&type='+TYPE+'&keyword='+KEYWORDS+'&key='+API_KEY) 
health_text = healthclubs.text 
healthjson = json.loads(health_text)


KEYWORDS = 'crossfit'
crossfit = requests.get(BASE_URL+'location='+LOCATION+'&radius='+RADIUS+'&type='+TYPE+'&keyword='+KEYWORDS+'&key='+API_KEY) 

cross_text = crossfit.text 
crossjson = json.loads(cross_text)

正如 V-R 在评论中建议的那样,您可以进一步定义函数,使事情更易于重用,从而允许您在应用程序的其他地方使用该函数

函数实现

def makeRequest(location, radius, type, keywords):
    BASE_URL = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
    API_KEY = 'AIzaSyDOwVK7bGap6b5Mpct1cjKMp7swFGi3uGg'
    result = requests.get(BASE_URL+'location='+location+'&radius='+radius+'&type='+type+'&keyword='+keywords+'&key='+API_KEY)
    jsonResult = json.loads(result)
    return jsonResult

函数调用

json = makeRequest('38.9208,-77.036', '2500', 'gym', '')

如果有问题请告诉我