Search code examples
python-3.xpymysql

pymysql: hide credential of my file


I have the following code:

from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://edamame:mypassword@1.2.3.4:3306/mydb')

I want to hide the part: edamame:mypassword@1.2.3.4:3306/mydb . Probably put into another file which is not committed to the repo.

I could just read in strings from another file, but I am wondering what is the better practice or design to achieve this? Thank you!


Solution

  • Yep, that's the right idea. I like yaml for basic config files, but you could use whatever format you'd like. If you use yaml, it would go something like this:

    1. Make a yaml file outside your repo with appropriate read/write/execute permissions.

      database_info:
          username: edamame
          password: mypassword
          host: 1.2.3.4
          port: 3306
          database: mydb
    2. Import with PyYAML.

      import yaml
      with open('your/file/path/here/db_config.yaml', 'r') as infile:
          db_cfg = yaml.safe_load(infile)
    3. Access the variables and populate your string (I usually wrap this in a function):

      engine = create_engine(
          'mysql+pymysql://{}:{}@{}:{}/{}'.format(
              db_cfg['database_info']['username'],
              db_cfg['database_info']['mypassword'],
              db_cfg['database_info']['host'],
              db_cfg['database_info']['port'],
              db_cfg['database_info']['database']
          )
      )

    Make sure your config file is not in the repo and that the directory/file permissions are correct. If you're building a web application, another good option are environment variables. You can access those using Python's os library.