python-dotenv的使用

  项目地址:https://github.com/theskumar/python-dotenv

  首先看一下github上项目的介绍:

  Reads the key,value pair from .env and adds them to environment variable. 

  大概意思就是在我们做项目时,我们可以把所有用到的环境变量写到.env文件里,然后以k,v的方式读取作为环境变量。

举个例子Python连接postgresql数据库:

python代码:

#coding:utf-8
import psycopg2 
from dotenv import find_dotenv,load_dotenv
import os
load_dotenv(find_dotenv())
conn=False
conn = psycopg2.connect(os.environ.get('URL'))
if conn:
        print '连接成功!'

.env内容:

URL=postgresql://postgres:123456@127.0.0.1/postgres

这样我们的项目迁移到不同的环境时只需要更改一下.env的内容就可以了,代码执行时会自动从.env文件里读取所需要的配置信息。

原文地址:https://www.cnblogs.com/liangping/p/7596265.html