Skip to content

Instantly share code, notes, and snippets.

@s-u
Last active June 8, 2020 06:12
Show Gist options
  • Save s-u/4fda8f97f2fca6b924fadcbe042cc6b8 to your computer and use it in GitHub Desktop.
Save s-u/4fda8f97f2fca6b924fadcbe042cc6b8 to your computer and use it in GitHub Desktop.
start_api_3.R
library(randomForest)
library(jsonlite)
# wczytanie modelu
model <- readRDS("model_rf.RDS")
# API - metody
predict_iris <- function(df) {
df <- as.data.frame(df)
## this is a bug in the client, it uses wrong names - so we have to fix it
names(df) <-
c("Sepal.Length","Sepal.Width",
"Petal.Length","Petal.Width")
pred <- as.character(predict(model, df))
# The python server only responds with the prediction
# we could spit out the whole row, if that was desired:
#jsonlite::toJSON(cbind(df, Species=pred))
}
alive <- function()
"I'm alive!"
add_floats <- function(a, b)
as.numeric(a) + as.numeric(b)
.http.request <- function(path, query, body, headers) {
what <- if (length(body)) jsonlite::fromJSON(rawToChar(body)) else list()
## /add abuses path as arguments...
pc <- strsplit(path, "/")[[1]][-1]
as.character(switch(pc[1],
iris = predict_iris(what),
alive = alive(),
add = add_floats(pc[2], pc[3])))
}
Rserve:::run.Rserve(http.port=8092)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment