ruby-on-rails 是否可以使用dotenv将JSON文件存储到ENV变量中?

kcugc4gi  于 2022-11-19  发布在  Ruby
关注(0)|答案(5)|浏览(141)

我在Rails应用程序中使用Google Drive API。API工作正常。我有以下client_secret. json文件:

{
  "type": "service_account",
  "project_id": "gobirdie-landing-page",
  "private_key_id": "xxxxx",
  "private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
  "client_email": "xxxxxxx@gobirdie-landing-page.iam.gserviceaccount.com",
  "client_id": "xxxxxxxxx",
  "auth_uri": "xxxxxx",
  "token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx"
}

在我的控制器中调用

@session = GoogleDrive::Session.from_service_account_key("client_secret.json")

有了这个配置没有问题,我设法使用API。但是,我想把我的JSON存储在.env文件中,如下所示:

CLIENT_SECRET = "{
  "type": "service_account",
  "project_id": "gobirdie-landing-page",
  "private_key_id": "xxxxx",
  "private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
  "client_email": "xxxxxxx@gobirdie-landing-page.iam.gserviceaccount.com",
  "client_id": "xxxxxxxxx",
  "auth_uri": "xxxxxx",
  "token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx"
}"

并在控制器中以这种方式调用它

@session = GoogleDrive::Session.from_service_account_key(ENV['CLIENT_SECRET'])

还是这样

@session = GoogleDrive::Session.from_service_account_key(JSON.parse(ENV['CLIENT_SECRET']))

但这两种方法都不管用。所以我的问题是:“是否可以将JSON文件存储在ENV变量中?”

4nkexdtk

4nkexdtk1#

将JSON对象转换为字符串并存储在ENV中
可以使用JSON.dump将JSON对象转换为字符串
然后在控制器JSON.parse(ENV['CLIENT_SECRET'])

或者

您可以在initializers文件夹中创建google_session.rb

$google_session = GoogleDrive::Session.from_service_account_key(
   # config goes here
)

在控制器中,您可以访问全局变量$google_session

zbsbpyhn

zbsbpyhn2#

您可以将项目放在一行中,例如:

VITE_FIREBASE={"apiKey":"slslsls","slsls":"lelsls"}

您只需要确保您的键中有引号
并像这样获取它们(SvelteKit示例):

const p = process?.env ? process.env : import.meta.env;

const firebase_config = JSON.parse(p.VITE_FIREBASE);

J型

7fyelxc5

7fyelxc53#

是的。可以将json文件存储在变量中。但是需要做一个小改动:

\\\"type\\\": \\\"service_account\\\",

对json的花括号内的每个双引号执行此操作。

n6lpvg4x

n6lpvg4x4#

我提出的解决方案是对json对象进行基本编码并存储它,然后根据使用它的请求对其进行解码。

klsxnrf1

klsxnrf15#

您必须缩小JSON并将所有\n更改为\\n

CLIENT_SECRET={"type":"service_account","project_id":"gobirdie-landing-page","private_key_id":"xxxxx","private_key":"-----BEGIN PRIVATE KEY-----\\nxxxxx\\n-----END PRIVATE KEY-----\\n","client_email":"xxxxxxx@gobirdie-landing-page.iam.gserviceaccount.com","client_id":"xxxxxxxxx","auth_uri":"xxxxxx","token_uri":"xxxxxxx","xxxxxxxx":"xxxxxxxxx"}

相关问题