How to hide you API key with Python

AI悦创原创2022年6月21日
大约 1 分钟

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:

API_KEY="abcd123"

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
load_dotenv()
API_KEY = os.getenv("API_KEY")

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

欢迎关注我公众号:AI悦创,有更多更好玩的等你发现!

公众号:AI悦创【二维码】

AI悦创·编程一对一

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

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

方法一:QQopen in new window

方法二:微信:Jiabcdefh

https://medium.com/@alexbebereche/how-to-hide-you-api-key-with-python-5cc63d2a6c45open in new window

评论
Powered by Waline v2.6.1