How to hide you API key with Python

AI悦创原创外文文章外文文章大约 2 分钟...约 460 字

Sometimes you need to store sensitive information in your code, such as passwords or API keys, and the cleanest way to do it in Python is using the os and dotenv modules.

For that, you will need to install the dotenv module, while the os module is a standard Python module and needs no installation.

In the command line, you enter:

pip install python-dotenv

or for Python 3

pip3 install python-dotenv

Let’s say the content of the .env file is:


A good practice is to include a .env.example file in your project, where you include an example for each one of the secret variables you are using. The content of the file would look like:

API_KEY="example key"

To load it in your python file, you should:

import os
from dotenv import load_dotenv
API_KEY = os.getenv("API_KEY")

There you go! Now, you are hiding you data properly!




AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh

C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh

方法一:QQopen in new window

方法二:微信:Jiabcdefh in new window

  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 按正序
  • 按倒序
  • 按热度