1

I have a couple scripts that I am working on that use a MYSQL DB for error logging and setting storage, and I would like a way to centrally and securely store MYSQL credentials for use in different places in the script, but I don't want to hold the connection open (open it once at the beginning of the script). Is there a best practice or a 'pythonic' way of doing this?

4

1 回答 1

0
class MyDB:
     def __init__(sql_server,user,password):
          self.server = sql_server
          self.user = user
          self.password = password

      def __getattr__(self,key):
           conn = MYSQLDB.connect(self.server,self.user,self.password)
           val = getattr(conn,key)
           conn.close()
           return val

settings.py

db = MyDb(my_server,my_user,my_pass)

other_script.py

from settings import db
db.whatever()
#or
import settings
settings.db.do_something()

maybe something like that ... and just pass that object around

the problem is you will still need to store the server and credentials somewhere in your program. there are some ways to obscure it but none are that good.

A. Use a simple encoding like base64 (not really encrypted, just encoded)

B. Use some kind of encryption library. This is encrypted and depending on method much harder to crack. unfortunately you still need the key embedded in the program (see A or B to "encrypt" the key)

于 2013-06-21T23:10:08.680 回答