简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM