python dotenv

    科技2026-10-03  12

    python dotenv

    教程| Python | Dotenv (Tutorial | Python | dotenv)

    In a previous post, I left a Discord token in the script. This is not the ideal way to code, especially if I don’t want to regenerate my tokens every time I share code. Using credentials and API tokens in your data science and programming projects is inevitable, but leaving them exposed is avoidable. Using the dotenv python module can help keep these sensitive bits of information safe from prying eyes.

    在上一篇文章中,我在脚本中留下了Discord令牌。 这不是理想的编码方式,尤其是如果我不想在每次共享代码时都重新生成令牌时,尤其如此。 在数据科学和编程项目中不可避免地使用凭证和API令牌,但是可以避免将它们暴露出来。 使用dotenv python模块可以帮助防止这些敏感信息被窥视。

    In a previous post I went through the steps to create a Discord bot using Discord.py in python. That example will be continued here, but the same idea can be used in any code that uses sensitive credentials or API tokens

    在上一篇文章中,我介绍了使用python中的Discord.py创建Discord机器人的步骤。 该示例将在此处继续,但是在使用敏感凭据或API令​​牌的任何代码中都可以使用相同的想法

    问题(The Problem)

    You have completed your brand new Discord bot and want to share your code with the world. Naturally, you upload it to GitHub and send out the link. Soon the bot stops working. Why? You left your API token in the code and someone took over your bot.

    您已经完成了全新的Discord僵尸程序,并想与世界共享您的代码。 自然,您将其上传到GitHub并发送链接。 僵尸程序很快就会停止工作。 为什么? 您将API令牌留在了代码中,然后有人接管了您的漫游器。

    You left your API token in the code and someone took over your bot

    您将API令牌留在了代码中,然后有人接管了您的漫游器

    API tokens give enormous amounts of power to control applications. With certain API’s, usage is monitored and you will even be billed for your usage! Fortunately Discord doesn’t charge you, but you still need to keep your credentials safe when using them in your coding projects.

    API令牌为控制应用程序提供了巨大的功能。 使用某些API,可以监控使用情况,甚至还会向您收取使用费用! 幸运的是,Discord不会向您收费,但是在您的编码项目中使用凭据时,仍然需要确保凭据安全。

    解决方案 (The Solution)

    Enter environment variables. Jim Medlock has a great explanation of what they are in his An Introduction to Environment Variables and How to Use Them. In that post he says:

    输入环境变量。 吉姆•梅德洛克(Jim Medlock)在“环境变量简介和如何使用它们”中有很好的解释。 他在那篇文章中说:

    An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time.

    环境变量是一种变量,其值通常在操作系统或微服务中内置的功能在程序外部设置。 环境变量由名称/值对组成,可以创建任何数字,并可以在某个时间点进行引用。

    We will use them to keep our Discord token safely out of our GitHub commits. This same process can be used for any other sensitive information you add to your bot, or even in other projects you are working on. For example, if you put your username and password in the bot’s code for web scraping, you will want to use dotenv to keep it safe.

    我们将使用它们来使Discord令牌安全地脱离GitHub提交。 可以将相同的过程用于添加到bot的任何其他敏感信息,甚至可以用于正在处理的其他项目。 例如,如果将用户名和密码放入用于网络抓取的bot代码中,则需要使用dotenv来确保其安全。

    安装 (Installation)

    Let’s start with installing the module. We can do this using package installer for python, more commonly known as pip.

    让我们从安装模块开始。 我们可以使用python的软件包安装程序(通常称为pip)来执行此操作。

    $ pip install python-dotenv I already have it installed, it’s that good! 我已经安装好了,太好了!

    .env设置 (.env Setup)

    Now let’s setup our .env file. This file should always live in the project folder’s top level folder or root directory. Create a new text file in that location, renaming it to .env. Windows will ask you to confirm that you want to change the file type. Click yes.

    现在,让我们设置.env文件。 该文件应始终位于项目文件夹的顶级文件夹或根目录中。 在该位置创建一个新的文本文件,将其重命名为.env 。 Windows会要求您确认要更改文件类型。 单击是。

    If Windows isn’t letting you name it .env, name it discord.env instead 如果Windows不允许您将其命名为.env,请改为将其命名为discord.env

    Next, open the .env file with a text editor. I prefer Atom or Notepad++, but Notepad will work just fine. By convention, environment variables are all uppercase with words separated by underscores. We can name ours TUTORIAL_BOT_TOKEN and paste our token in. Save and close the file.

    接下来,使用文本编辑器打开.env文件。 我更喜欢Atom或Notepad ++ ,但是Notepad可以正常工作。 按照惯例,环境变量都是大写的,单词之间用下划线分隔。 我们可以命名我们的TUTORIAL_BOT_TOKEN并粘贴我们的令牌。保存并关闭文件。

    TUTORIAL_BOT_TOKEN=NzUzNzU3Mjg0NTI1NTM5MzQ4.X1q1LA.4xD7lSQrN0EqJivrrogLUScNdfY

    添加到.gitignore (Add to .gitignore)

    Now my assumption is you are using GitHub as version control for your data science projects. If you aren’t, you should be! It is a great way to roll back changes to your code if something goes wrong. GitHub also enables collaboration with others. You wouldn’t want them to also have your token, so we have some work to do. If you don’t have a repository setup for the project or don’t know how to, don’t sweat it, I’ll cover this in another post. You can safely move on to the next section.

    现在,我的假设是您将GitHub用作数据科学项目的版本控制。 如果不是,那应该是! 如果出现问题,这是回滚对代码所做的更改的好方法。 GitHub还可以与他人进行协作。 您不希望他们也有您的令牌,因此我们需要做一些工作。 如果您没有该项目的存储库设置,或者不知道该怎么做,请不要大汗,我将在另一篇文章中介绍。 您可以安全地转到下一部分。

    GitHub will save all of the changes to the code, but we need to exclude the .env file as that is what contains our token. To make sure that the .env file is not committed to the repository, open up the .gitignore file in your project folder and add the following line.

    GitHub将保存对代码的所有更改,但是我们需要排除.env文件,因为这是包含令牌的内容。 要确保.env文件未提交到存储库,请在项目文件夹中打开.gitignore文件,并添加以下行。

    *.env

    Adding this line will ignore the .env file that we created earlier. By using the asterisk (*), we are excluding all files in the top level folder or root directory that have the .env extension from being committed to the repository.

    添加此行将忽略我们之前创建的.env文件。 通过使用星号(*),我们排除了顶级文件夹或根目录中.env扩展名为.env文件,这些文件不会提交到存储库。

    加载环境变量 (Loading Environment Variables)

    Now that we have the .env file with our sensitive information and it won’t get committed to your repository, we need to actually use it in our python script.

    现在,我们已经.env包含敏感信息的.env文件,并且该文件不会提交到您的存储库中,我们需要在python脚本中实际使用它。

    First we need to load the dotenv and os modules. For this example, we can add them to the script from my Hello World Discord.py Tutorial.

    首先,我们需要加载dotenv和os模块。 对于此示例,我们可以将它们添加到我的Hello World Discord.py Tutorial中的脚本中。

    # Importsfrom dotenv import load_dotenvimport os

    load_dotenv will be used to load the .env file to the environment variables. os will be used to refer to those variables in the code. Let’s start with load_dotenv. This will load the .env file.

    load_dotenv将用于将.env文件加载到环境变量中。 os将用于引用代码中的那些变量。 让我们从load_dotenv开始。 这将加载.env文件。

    # Credentialsload_dotenv('.env')

    To use the environment variable, we can use os.getenv in the client.run command at the end of the bot script.

    要使用环境变量,我们可以在bot脚本末尾的client.run命令中使用os.getenv 。

    client.run(os.getenv('TUTORIAL_BOT_TOKEN'))

    测试代码 (Testing the Code)

    Now that everything is setup, navigate to the bot script location in the command line, running the script to start the bot.

    现在已完成所有设置,请在命令行中导航到bot脚本位置,运行脚本以启动bot。

    $ cd path\to\bot$ python 02_Discord_dotenv.py

    You will see the bot name and ID printed to the console. Just to be thorough, hop into the server with the bot and test the !helloworld command, it should work perfectly!

    您将看到机器人名称和ID印在控制台上。 为了更全面,请使用bot跳入服务器并测试!helloworld命令,它应该可以正常运行!

    Unsurprisingly, the command works fine! 毫不奇怪,该命令可以正常运行!

    结束语 (Closing Remarks)

    The dotenv module is a great way to obscure sensitive information. It doesn’t have to be limited to use with Discord bots. Anywhere code is using login credentials, database connection information, API tokens, or anything else you don’t want to share with the world, put it in your .env file.

    dotenv模块是掩盖敏感信息的好方法。 并不仅限于与Discord机器人一起使用。 任何地方的代码都使用登录凭据,数据库连接信息,API令牌或您不想与世界共享的任何其他内容,请将其放入.env文件中。

    For more on the dotenv python module, check out the GitHub Repository which includes more documentation on the module.

    有关dotenv python模块的更多信息,请查看GitHub Repository ,其中包括有关该模块的更多文档。

    寻找更多的项目创意? (Looking for More Project Ideas?)

    Check out another of my posts to help generate some ideas where you can apply the concepts discussed here. Make your projects stand out on GitHub while keeping your credentials safe!

    请查看我的另一篇文章,以帮助产生一些想法,您可以在其中应用此处讨论的概念。 确保您的项目在GitHub上脱颖而出,同时确保您的凭据安全!

    翻译自: https://towardsdatascience.com/using-dotenv-to-hide-sensitive-information-in-python-77ab9dfdaac8

    python dotenv

    相关资源:python_dotenv-0.10.0-py2.py3-none-any.whl
    Processed: 0.010, SQL: 9