简体   繁体   English

在 Visual Studio 代码中导入文件

[英]importing a file within visual studio code

I'm trying to make a file within visual studio code that holds my API key and secret key.我正在尝试在 Visual Studio 代码中创建一个文件,其中包含我的 API 密钥和密钥。 so when I do future codes I can just import that file into my code without having to write my API keys every time.所以当我做未来的代码时,我可以将该文件导入到我的代码中,而不必每次都编写我的 API 密钥。

I've tried this我试过这个

api key = 'cewhjhbdhbd' secret key = 'jhewbduywevb' api 密钥 = 'cewhjhbdhbd' 密钥 = 'jhewbduywevb'

tried to save it.. it saved in documents and when I tried to import it nothing happened.. where am I going wrong?试图保存它..它保存在文档中,当我尝试导入它时,什么也没发生..我哪里出错了?

I am a beginner at coding so sorry if this is obvious.我是编码的初学者,如果这很明显,我很抱歉。

You can use environment variables for this.您可以为此使用环境变量。

import os

# Set environment variables
os.environ['API_USER'] = 'username'
os.environ['API_PASSWORD'] = 'secret'

# Get environment variables
USER = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')

You can then import this file or use the above block of code in your files.然后,您可以导入此文件或在文件中使用上述代码块。

Use an environment file like .env to store your API keys.使用.env 之类的环境文件来存储您的 API 密钥。 In a format like以类似的格式

ENVIRONMENT='DEVELOPMENT'
API_KEY='yourapikeygoeshere'
DEBUG=True
DB_NAME=''
DB_USER=''
DB_PASSWORD=''
DB_HOST='localhost'
DB_PORT='5432'

Then you can use packages like dotenv to access them.然后你可以使用像dotenv这样的包来访问它们。

from dotenv import load_dotenv
from pathlib import Path

dotenv_path = Path('path/to/.env')
load_dotenv(dotenv_path=dotenv_path)
API_KEY = os.getenv('API_KEY')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM