是否可以使用dotenv将JSON文件存储到ENV变量中? [英] Is it possible to store a JSON file to an ENV variable with dotenv?

查看:299
本文介绍了是否可以使用dotenv将JSON文件存储到ENV变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Rails应用程序中使用Google Drive API. API运行正常.我有以下client_secret.json文件:

I am using Google Drive API with my Rails application. The API is working fine. I have the following client_secret.json file:

{
  "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文件中,例如:

With this configuration no problem, I manage to use the API. However, I would like to store my JSON in the .env file like:

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"
}" 

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

And call it in the controller in this way

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

或者通过这种方式

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

但是两种方法都不起作用.所以我的问题是:是否可以将JSON文件存储在ENV变量中?"

But neither methods are working. So my question is : "Is it possible to store JSON file in an ENV variable ?"

推荐答案

将JSON对象转换为字符串并将其存储在ENV中

Convert the JSON object to string and store it in the ENV

您可以使用JSON.dump将JSON对象转换为字符串

You can use JSON.dump to convert JSON object to string

,然后在您的控制器JSON.parse(ENV['CLIENT_SECRET'])

或者

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

you can create a google_session.rb inside initializers folder

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

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

and in your controller you will have access to $google_session global variable

这篇关于是否可以使用dotenv将JSON文件存储到ENV变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆