如何在 Rails 中存储 API 的密钥? [英] How do I store keys for API's in Rails?

查看:37
本文介绍了如何在 Rails 中存储 API 的密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 api 需要在我的应用程序的各个部分进行集成和调用.

I have several api's that I am integrating with and need to call in various parts of my application.

存储密钥、用户/密码或令牌信息(例如配置文件)的方式是什么,然后我如何调用它们以在应用程序的其他部分中使用?

What is the way to store the keys, the user/password, or token information, say, a configuration file and then how do I call them for use in other parts of the application?

谢谢.

推荐答案

最简单的方法是将信息作为常量存储在各种环境文件中.这样您就可以使用不同的帐户进行开发、生产等.

Easiest is to store the info as constants in your various environment files. That way you can use different accounts for development, production, etc.

# Eg
# development/environment.rb
....
API_1_USER = "user101"
API_1_PW = "secret!"

另一种方法是创建一个 yaml 文件,然后在您的应用程序登录到 api 时读取它.这是 rails 本身在 config/databse.yml 文件中使用的样式

Alternative is to create a yaml file, then read it when your app signs in to an api. This is the style used by rails itself with the config/databse.yml file

添加

您还可以使用散列或嵌套散列将其存储为常量.

You can also store as a constant using a hash or nested hash.

# Eg
# development/environment.rb
....
API_1 = {"user" => "user101", "pw" => "secret!"}
API_2 = {"user" => "user102", "pw" => "double_secret"}

# or nested hashes
API_KEYS = {
             "api_1" => {"user" => "user101", "pw" => "secret!"},
             "api_2" => {"user" => "user102", "pw" => "double_secret"}}

# using them in another file:
foo.signin(API_1['user'], API_1['pw'])
# or
foo.signin(API_KEYS["api_1"]['user'], API_KEYS["api_1"]['pw'])

# note, I use string constants instead of symbols to save vm (since the hash is
# not referenced more than once or twice). You could also use
# symbols as the keys, especially if the hash will be referenced often:
API_1 = {:user => "user101", :pw => "secret!"}

这篇关于如何在 Rails 中存储 API 的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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