【问题标题】:How can I store a userid and password in SQLite database from my python application?如何从我的 python 应用程序将用户名和密码存储在 SQLite 数据库中?
【发布时间】:2020-12-14 00:15:35
【问题描述】:

我不是 python 专家,我只是在我的 python 配置文件中静态存储了一个用户名和密码,应用程序使用这个凭据来 FTP 一些文件。 我无法保留代码中显示的静态密码,我应该将其存储在 SQLite 之类的地方。 如何从我的 python 应用程序将用户名和密码存储到 SQLite?代码是什么? 我想凭据只存储在数据库中,然后每次需要时都可以检索。 另外,存储后如何从数据库中检索它? 有没有办法加密密码呢?以增强安全性。 PS:我也在使用 Flask。 谢谢大家,现在我的python文件中有以下代码:

    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')

【问题讨论】:

    标签: python python-3.x python-2.7 sqlite flask-sqlalchemy


    【解决方案1】:

    首先在sqlite中创建一个凭证表,并在其中存储“id”和“password”。 然后从存储了您的 id 和密码的 sqlite db 读取密码,请使用以下代码:

    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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-13
      • 2017-12-02
      • 2011-10-21
      • 2013-10-31
      • 1970-01-01
      • 2011-08-28
      • 2023-02-07
      • 1970-01-01
      相关资源
      最近更新 更多