Environment Variables

Environment variables can be accessed directly from within models.

import os
value1 = os.environ["DB_PASSWORD"]

#for json variables, import json
value2 = json.loads(os.environ["json_var"])
value <- Sys.getenv("DB_PASSWORD")

# for json variables, use jsonlite
value2 <- jsonlite::fromJSON(Sys.getenv("json_var"))

Next, set the environment variable value in the Model Settings page

Below, a simple model that prints out our environment variables DB_PASSWORD and

from yhat import Yhat, YhatModel , preprocess
import os
import json

class my_env_vars(YhatModel):
    @preprocess(in_type=dict, out_type=dict)
    def execute(self, data):
        value1 = os.environ["DB_PASSWORD"]
        value2 = json.loads(os.environ["json_var"])
        return { "my_db_password is": value1,"jsondata":value2 }


yh = Yhat("USERNAME", "API_KEY", "http://sandbox.yhathq.com/")
yh.deploy  ("my_env_vars", my_env_vars, globals())

## Model Response:

{
  "result": {
    "jsondata": {
      "a": [
        1
      ],
      "b": [
        2
      ],
      "c": [
        3
      ]
    },
    "my_db_password is": "abcd1234"
  },
  "version": 4,
  "yhat_id": "7ea280ec7bed5b1bf973dd66bcba7d90",
  "yhat_model": "my_env_vars"
library(jsonlite)
library(yhatr)

model.predict <- function(request) {

  #read back in the JSON environment variable
  jsonvar <- jsonlite::fromJSON(Sys.getenv("json_var"))
  c("db-password"=Sys.getenv('DBPASSWORD'),jsonvar)
}


yhat.config  <- c(
  username="USERNAME",
  apikey="API_KEY",
  env="http://sandbox.yhathq.com/"
)
yhat.deploy("get_env_var")

## Model Response

{
  "result": {
    "a": 1,
    "b": 2,
    "c": 3,
    "db-password": "abcd1234"
  },
  "version": 6,
  "yhat_id": "4497870b83ce81945146177b10c46e07",
  "yhat_model": "get_env_var"
}

results matching ""

    No results matching ""