我怎样将我的凭证添加到 .gitignore,但仍然可以执行我的 Python?

huangapple go评论61阅读模式
英文:

How can I add my credentials into .gitignore but still execute my python?

问题

我在如何将我的凭据添加到.gitignore文件中时感到困惑,因为它们存储在我的配置文件中。我在我的配置文件中存储了数据库凭据,并在下面的代码中使用它们:

import os 
import json
import platform
import logging
import pymysql as pm
import boto3

# ...(代码省略)...

class ClassName:
    # ...(代码省略)...

    def DB_connection(self):
        # ...(代码省略)...
        dbUserName = "user"
        # ...(代码省略)...
        dbPassword = result["pass"]
        # ...(代码省略)...

# ...(代码省略)...

def main():
    # ...(代码省略)...
    vfc=(cwd+"/config"+".json")
    # ...(代码省略)...

我的配置信息以json格式存储在这里:

{
    "exceptions":{
        "database-secrets":{
            "host": "host",
            "db": "db",
            "port": port
        },
        "functions":{
            "func1": true,
            "func2": true,
            "func3": true
        }
    }
}

我必须将它们添加到.gitignore中,因为凭据将根据级别不同而不同。

英文:

I am confused on how to add my credentials to .gitignore when they are in my config file. I have database credentials stored in my config file and they are used to execute my code below:

import os 
import json
import platform
import logging
import pymysql as pm
import boto3

class ClassName:
    env=None
    config=None

    def __init__(self, env_filename):
        self.env=env_filename
        self.config=self.get_config()

    def get_config(self):
        with open(self.env) as file_in:
            return json.load(file_in)
        
    def is_Windows():
        if "win" in (platform.system().lower()):
            return True
        else:
            return False

    def DB_connection(self):
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        connection = None
        try:
            config=ClassName.get_config(self)
            host=config["exceptions"]["database-secrets"]["host"]
            port=config["exceptions"]["database-secrets"]["port"]
            database=config["exceptions"]["database-secrets"]["db"]

            # retrieve DB password from secrets manager by invoking exceptions lambda function
            dbUserName = "user"
            lambdaFunctionName = "exceptions"
            client = boto3.client('lambda')
            response = client.invoke(FunctionName=lambdaFunctionName)
            result = json.loads(response['Payload'].read().decode())
            dbPassword = result["pass"]

            connection = pm.connect(user=dbUserName,password=dbPassword,host=host,port=port,database=database)
    
            logger.info("Successfully connected to database")

        except Exception as e:
            logger.error("Unable to connect to database: %s", str(e))
        
        return connection
    

    def run_all(self):
        def func1(self):
            func1_INSERT_QUERY = "CALL sp_func1_Insert_Daily_Records();"
            func1_EXCEPTIONS_QUERY = "CALL sp_func1_Exceptions();"
            vfcaa = self.config["verafin-exceptions"]["functions"]["func1"]
            if vfcaa:
                with self.DB_connection() as cnxn:
                    with cnxn.cursor() as cur:
                        try:
                            cur.execute(func1_INSERT_QUERY)
                            print("func1 insertion query ran successfully, {} records updated.".format(cur.rowcount), '\n')

                            cur.execute(func1_EXCEPTIONS_QUERY)
                            print("func1 exceptions query ran successfully, {} exceptions updated.".format(cur.rowcount), '\n')
                            data=cur.fetchall()                     
                            for row in data:
                                for col in row:
                                    print (col, end=' ')
                                print('\n')

                        except pm.Error as e:
                            print(f"Error: {e}")

                        except Exception as e:
                            logging.exception(e)

                        else:
                            cnxn.commit()
        func1(self)

        def func2(self):
            func2_INSERT_QUERY = "CALL sp_func2_Insert_Daily_Records();"
            func2_EXCEPTIONS_QUERY = "CALL sp_func2_Exceptions();"
            vfj = self.config["verafin-exceptions"]["functions"]["func2"]
            if vfj:
                with self.DB_connection() as cnxn:
                    with cnxn.cursor() as cur:
                        try:
                            cur.execute(func2_INSERT_QUERY)
                            print("func2 insertion query ran successfully, {} records updated.".format(cur.rowcount), '\n')

                            cur.execute(func2_EXCEPTIONS_QUERY)
                            print("func2 exceptions query ran successfully, {} exceptions updated.".format(cur.rowcount), '\n')
                            data=cur.fetchall()                     
                            for row in data:
                                for col in row:
                                    print (col, end=' ')
                                print('\n')

                        except pm.Error as e:
                            print(f"Error: {e}")

                        except Exception as e:
                            logging.exception(e)

                        else:
                            cnxn.commit()
        func2(self)

        def func3(self):
            func3_INSERT_QUERY = "CALL sp_func3_Insert_Daily_Records();"
            func3_EXCEPTIONS_QUERY = "CALL sp_func3_Exceptions();"
            vfl = self.config["verafin-exceptions"]["functions"]["func3"]
            if vfl:
                with self.DB_connection() as cnxn:
                    with cnxn.cursor() as cur:
                        try:
                            cur.execute(func3_INSERT_QUERY)
                            print("func3 insertion query ran successfully, {} records updated.".format(cur.rowcount), '\n')

                            cur.execute(func3_EXCEPTIONS_QUERY)
                            print("func3 exceptions query ran successfully, {} exceptions updated.".format(cur.rowcount), '\n')
                            data=cur.fetchall()                   
                            for row in data:
                                for col in row:
                                    print (col, end=' ')
                                print('\n')

                        except pm.Error as e:
                            print(f"Error: {e}")

                        except Exception as e:
                            logging.exception(e)

                        else:
                            cnxn.commit()
        func3(self)

def main():
    cwd=os.getcwd()
    if "win" in (platform.system().lower()):
        vfc=(cwd+"\config"+".json")
    else:
        vfc=(cwd+"/config"+".json")
    ve=ClassName(vfc)
    ve.run_all()
if __name__ == "__main__":
    main()

My config has info stored here in json format:

{
    "exceptions":{
        "database-secrets":{
            "host": "host",
            "db": "db",
            "port": port
        },
        "functions":{
            "func1": true,
            "func2": true,
            "func3": true
        }
    }
}

I have to add them into .gitignore because the credentials will differ depending on the levels.

答案1

得分: 1

你可以将配置文件添加到.gitignore中,然后在将应用程序部署到服务器后,可以手动在服务器上添加一个新的配置文件以使其正常工作。

这样,您的凭据不会暴露在您的git存储库中。
这是许多人使用的标准程序,但现在更好地由第三方服务管理,例如Azure KeyVault等。您可以查看一下这方面的信息。

英文:

You can add your config file to .gitignore and then once you deploy your app in the server, you can manually add a new config file in the server to get it working.

This way your credentials are not exposed in your git repo.
This is a pretty standard procedure which many people use, but nowadays its better managed by third party services such as Azure KeyVault etc. You could take a look into that.

答案2

得分: 1

你可以选择不将凭证推送到Git。在部署过程中,可以将此凭证文件注入文件系统,并像往常一样在代码中引用它。

也许你可以考虑使用类似 https://www.vaultproject.io/ 的解决方案。

英文:

You could just not push the credentials to git. During the deployment, you can inject this credential file into the file system and reference it in the code as usual.

maybe you could consider using a solution like https://www.vaultproject.io/ as well

huangapple
  • 本文由 发表于 2023年6月8日 05:39:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定