Skip to content Skip to sidebar Skip to footer

How Do I Save Database Configuration Without Writting Them On My Python File

I have a python application that requires database credentials, the code looks something like this. def __init__ (self): self.conn = pymysql.connect('localhost','user','pass',

Solution 1:

you mean envirnment variables?

you can access them like this:

import osos.getenv('DATABASE_NAME')

Solution 2:

What I have been doing in similar cases is to keep a separate module with all config settings, declared as "constant" variables, like this:

#global_setup.py (separate module) MY_DB_SERVER = "localhost"MY_DB_USER = "user"MY_DB_PASS = "pass"MY_DB_DB = "db"

Then you import everything from that module whenever you need to use those constants. You can create a separate version of that file whitout sensitive info in order to upload to public Git servers.

# main modulefrom global_setup import *

def__init__ (self):
    self.conn = pymysql.connect(MY_DB_SERVER, MY_DB_USER, MY_DB_PASS, MY_DB_DB, use_unicode=True, charset="utf8")

Now, take care in case your application will be deployed in an environment where the user should not be able to access the database itself, or if it will be accessing the database through a non encrypted connection. You may need more security measures in those cases, like connection through SSL, or having a server-side application creating an API.

Solution 3:

You can use envparse module. It allows you to use environment variables and cast them to the proper types.

You can add variables for each value, as database name, database host, or create a postprocessor and define the variable as an URL:

from envparse import env  

db_host = env(DB_HOST, 'localhost')
db_port = env.int(DB_PORT, 3306)
db_user = env(DB_USER)
db_pass = env(DB_PASS)
db_name = env(DB_NAME)

conn = pymysql.connect(db_host,db_user,db_pass,db_name, use_unicode=True, charset="utf8")

Solution 4:

There is a module ConfigParser in python to create .ini file and save credentials and read when you required them.

https://docs.python.org/3/library/configparser.html

Post a Comment for "How Do I Save Database Configuration Without Writting Them On My Python File"