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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With