I’m trying out Google’s geo APIs and to try and respect good practice I’m trying to keep my api key out of my GitHub repo by putting it in a file (api_keys.py
).
coordinates_api.py
calls api_keys.py
with import api_keys
to retrieve the key and call the APIs, and when testing coordinates_api.py
everything works fine and I get my coordinates printed as I expect.
When I test main.py
though, which calls coordinates_api.py
, I get the error:
Traceback (most recent call last):
File "c:UsersmeDocumentsProjectsGitProjectNamesrcmain.py", line 1, in <module>
from apis import *
File "c:UsersmeDocumentsProjectsGitProjectNamesrcapiscoordinates_api.py", line 2, in <module>
import api_keys
ModuleNotFoundError: No module named 'api_keys'
I don’t understand why my api_keys
module is not recognized by main.py
Here’s the code for coordinates_api.py
:
import requests
import api_keys
class CoordinatesAPI:
def __init__(self, api_key=None):
self.api_key = api_keys.geo
def get_coordinates(self, address):
base_url = "https://maps.googleapis.com/maps/api/geocode/json"
params = {
"address": address,
"key": self.api_key
}
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
if data['status'] == 'OK':
location = data['results'][0]['geometry']['location']
return location['lat'], location['lng']
else:
raise Exception(f"Error from API: {data['status']}")
else:
raise Exception(f"HTTP error: {response.status_code}")
And for main.py
:
from apis import coordinates_api
if __name__ == "__main__":
address = "1600 Amphitheatre Parkway, Mountain View, CA"
CA1 = coordinates_api.CoordinatesAPI()
lat, lng = CA1.get_coordinates(address)
print(f"Latitude: {lat}, Longitude: {lng}")
(Here I also tried playing a bit with the import but also e.g. from apis import *
gives the same error. Rather than doing trial and error I would like to properly understand what I’m missing here)
This is what my tree looks like:
│ main.py
│
├───apis
│ │ api_keys.py
│ │ coordinates_api.py
│ │ __init__.py
user24196311 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
If you always mean to use your package from outside of its folder, you can simply substitute import api_keys
with from apis import api_keys
or from . import api_keys
.
Otherwise you can can add apis
to PYTHONPATH
environment variable, so that modules can be searched inside this folder, without having to know from where the script is run.