Skip to content

Commit b4dbde1

Browse files
authored
Merge pull request #34 from imohitmayank/mohit-25092024-updates
Added Handling Secrets and Keys section in good practices
2 parents 2645337 + 009fe12 commit b4dbde1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

docs/data_science_tools/python_good_practices.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,34 @@ logger.setLevel(logging.INFO)
286286
!!! note
287287
Remember to switch to another VE when you start working on another project or/and to deactivate the VE when you want to move to base VE.
288288

289+
### Handling Secrets and Keys
290+
291+
- While working on a project, we often need to use some secret keys or passwords, like API keys, database passwords, etc. It is a good practice to store these keys in a separate file, which is not committed to the version control system. This file is usually named `.env` and is stored at the root of the project directory. The `.env` file contains the keys in the form of `KEY=VALUE` pairs. For example,
292+
293+
``` python linenums="1"
294+
API_KEY=1234567890
295+
DB_PASSWORD=abcd1234
296+
```
297+
298+
- To access these keys in the code, we can use the `python-dotenv` package to read the `.env` file and store the keys in the environment variables. Then we can use `os` module to read the environment variables. For example,
299+
300+
``` python linenums="1"
301+
import os
302+
from dotenv import load_dotenv
303+
304+
# load the .env file
305+
load_dotenv()
306+
307+
# access the keys
308+
api_key = os.getenv('API_KEY')
309+
db_password = os.getenv('DB_PASSWORD')
310+
```
311+
312+
- The `.env` file should be added to the `.gitignore` file to prevent it from being committed to the version control system. This ensures that the secret keys are not exposed to the public.
313+
314+
!!! Hint
315+
If you are using AI coding assistant like Github CoPilot, make sure to exclude the `.env` files in the settings so that it can't access the keys.
316+
289317
### Type Hints and Data Validation
290318

291319
- Python comes with dynamic variable type support, i.e. you can execute code `x=1` and `x='a'` one after the another and the it will still work. This is in contrast with languages like Java and C++ where you have to specify the type explicitly, for example `int a = 1`. While this feature makes Python easier to use and more dynamic, it comes at the cost of clarity and complexity. Now, let's talk about some good practices to mitigate this.

0 commit comments

Comments
 (0)