'How can I store a userid and password in SQLite database from my python application?
I'm not a pro in python, I just have a username and password stored statically in my python config file, the app use this credentials to FTP some files. I cannot keep a static password shown in the code, I should store it somewhere like SQLite. How can I store a username and pw to SQLite from my python app? what is the code? I suppose the credentials are stored just ones in the db and then retrieved every time you need. Also how do I retrieve it from the db after has been stored? Is there a way to encrypt the password also? to enhance the security. PS: I'm also using Flask. Thank you all, for now I have the following code in my python file:
DICP_FTP_DESTINATION_USER = 'yw\mligi'
DICP_FTP_DESTINATION_PSW = 'blablablabla'
DICP_FTP_DESTINATION_DIR = '/'
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
Solution 1:[1]
First create a credential table in sqlite and store "id" and "password" in it. then to read password from you sqlite db where you have your id and password stored use the below code:
import sqlite3
import hashlib
def connect_dbs():
return sqlite3.connect("Database_name.db")
#function to fetch password
def password_fetch(id):
connect_ = connect_dbs()
cur = connect_.cursor()
try:
cur.execute("select password from credential_table_name where id=?",(id,))
data=cur.fetchone()
if data != None:
return {'pwd':data}
else :
return {'status':'400'}
except Exception as e:
return {'Error',str(e)}
# function to insert into table
def Insert(id,password):
connect_ = connect_dbs()
cur = connect_.cursor()
try:
cur.execute("Insert into credential_table_name values (?,?)",(id,hashing(password)))
connect_.commit()
return {'status':'Data inserted successfully'}
except Exception as e:
return {'Error',str(e)}
#function to encrypt your password
def hashing(pwd):
hash_object = hashlib.md5(bytes(str(pwd), encoding='utf-8'))
hex_dig= hash_object.hexdigest()
return hex_dig
if __name__ == "__main__":
print(password_fetch(12345))
print(Insert(12346,'PQRSTWse12'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tomato Master |