EHM
EHM

Reputation: 959

Secure way of accessing a PostgreSQL database using python

So I have a flask web application that does basic database operations. I am using a PostgreSQL database. And I am using psycopg2 to access it. here is the code snippet for retrieving my data.

import psycopg2
connection = psycopg2.connect(user="sysadmin",
                                  password="mypass",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="myData")

That isn't my exact code but it will demonstrate my question. As you could see my database password and username are visible for any one who has access to my server code. But i don't feel writing the database password inside the program is a secure way! so i was hoping if any one could point out any other ways. How do professional web applications like Google and Facebook do it?

Upvotes: 0

Views: 1502

Answers (2)

Marlone
Marlone

Reputation: 101

I was recently learning flask and had this question. I ended up using a json "secrets" file to hold login info as well as secret keys.

secretfiles.json

  {
  "web": {
    "app_id": "randomlongid",
    "app_secret": "randomlongkey",
    "user_name": "ausername",
    "user_pw": "randompassword"
  }
}

I then imported into my app.

import json
import psycopg2

MY_PASS = json.loads(open('secretfiles.json', 'r').read())['web']['user_pw']

connection = psycopg2.connect(user="sysadmin",
                                  password=MY_PASS,
                                  host="127.0.0.1",
                                  port="5432",
                                  database="myData")


I would then add the file name or just *.json to my .gitignore

However I have been looking for a good explanation on using environmental variables like the one infobiac just linked so I'll most likely use that method going forward.

Upvotes: 2

infobiac
infobiac

Reputation: 163

One thing you might consider are environment variables, which would allow you to define secret values in their environment, rather than in the code itself. In python, you can access an environment with os.environ.get("variablename"); a full tutorial for working with them in python is available here. This is how many services choose to manage secrets, and is the default for services like heroku.

Upvotes: 3

Related Questions