Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide google map api key in django before pushing it on github?

This is my google address api script which contains the api key

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=api_key&libraries=places&callback=ActivatePlacesSearch">

I have used .env file in project directory to hide sensitive info from settings.py file. How can I use .env file to hide my api key from my template?

like image 556
imsaiful Avatar asked Aug 26 '18 23:08

imsaiful


People also ask

How do I hide my API key in github?

The only way to hide it is to proxy your request through your own server. Netlify Functions are a free way to add some simple backend code to a frontend app. This is this method I used while learning to program in college, where I needed to share my progress with my peer group without disclosing my API keys.

Should Google API key be hidden?

API keys are not strictly secret as they are often embedded into client side code or mobile applications that consume Google Cloud APIs. Still,they should be secured and should never be treated as public information.


1 Answers

Define a variable in your .env file, for example:

GOOGLE_MAPS_API_KEY="your_key"

Then in myproject/settings.py:

GOOGLE_MAPS_API_KEY = os.environ.get('GOOGLE_MAPS_API_KEY')

Then in your views.py file:

from django.conf import settings

def my_view(request):
    context = {
        'api_key': settings.GOOGLE_MAPS_API_KEY
    }
    return render('template.html', context)

then you can access api_key in the template.

Note (thanks to trixn in the comments): Make sure the .env file is included in your .gitignore file so that it doesn't get checked into source control and leak your token. If you've used a standard .gitignore for Python, it should already be included.

like image 116
Henry Woody Avatar answered Oct 08 '22 05:10

Henry Woody