Jon
Jon

Reputation: 1801

How to load GOOGLE_API_KEY with Python and Bokeh

I am trying to teach myself to use Bokeh with the example on the Bokeh website shown below,

Bokeh Tutorial

I have written the following code;

import os
from bokeh.models import GMapOptions
from bokeh.plotting import gmap

map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11)

# Replace the value below with your personal API key:
api_key = os.environ["GOOGLE_API_KEY"]

p = gmap(api_key, map_options, title="Austin")

data = dict(lat=[ 30.29,  30.20,  30.29],
            lon=[-97.70, -97.74, -97.78])

p.circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, source=data)

show(p)

However, when I run the script it fails with the following Error

Traceback (most recent call last):
  File "/Users/jonwebb/Desktop/Tests/property/properties.py", line 71, in <module>
    api_key = os.environ["GOOGLE_API_KEY"]
  File "/usr/local/Cellar/[email protected]/3.9.1_2/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'GOOGLE_API_KEY'

This example comes straight from the Bokeh tutorial, so it should work. Does anyone know the cause of this issue?

Upvotes: -1

Views: 5757

Answers (3)

Jo&#227;o Victor
Jo&#227;o Victor

Reputation: 161

you can use the python-dotenv and create a .env file on root of project, load the env and use os.getenv('env_name')

import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
os.getenv('GOOGLE_API_KEY')

in your .env file:

GOOGLE_API_KEY=something-goes-here

check the lib here

Upvotes: 1

Botond
Botond

Reputation: 204

You can either replace

api_key = os.environ["GOOGLE_API_KEY"]

with

api_key = "YOUR_API_KEY"

"YOUR_API_KEY" should be replaced with your actual API key. You could also set up the environmental variable GOOGLE_API_KEY to be your API Key.

Upvotes: 1

bigreddot
bigreddot

Reputation: 34608

os.environ is the Python standard library mechanism to access OS environment variables. So to use the code above as-is, set the GOOGLE_API_KEY environment variable (this varies by OS and by shell, you will have to look up specifics for your situation).

But also note that nothing in Bokeh requires you to do things this way at all. This example uses environment variable because it is convenient. But ultimately, all Bokeh cares about is that you pass the API key string as a parameter to the gmap function. How you get the string is up to you, if you don't want to use an environment variable, you could read it from a file, or hard-code it in the script (but avoid checking it in to revision control if you do this).

Upvotes: 0

Related Questions