文章目录
- 一、安装R语言环境
- 二、qdiabetes
- 三、安装Python环境
- 四、提供Rest接口
一、安装R语言环境
- 安装
sudo apt-get update
sudo apt-get install r-base
- /home/rscript/script.R
# script.R
cat("Hello, World!\n")
- 测试
Rscript /home/rscript/script.R
二、qdiabetes
- 安装
R
install.packages("QDiabetes")
q()
- /home/rscript/test.R
# script.R
library(QDiabetes)
QDR2018A(sex = "Female", age = 60, bmi = 35)
QDR2018B(sex = "Male", age = 60, bmi = 35, fpg = 6)
QDR2018C(sex = "Male", age = 60, bmi = 35, hba1c = 42)
- 测试
Rscript /home/rscript/test.R
三、安装Python环境
- /root/.pip/pip.conf
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = https://pypi.tuna.tsinghua.edu.cn
- 安装
apt install python3-pip
pip install --upgrade pip
pip install --upgrade setuptools
pip install fastapi
pip install uvicorn[standard]
pip install rpy2
- /home/python/test_rscript.py
#!usr/bin/env python3
import rpy2.robjects as ro
ro.r('source("/home/rscript/test.R")')
result = ro.r['QDR2018B'](sex = "Female", age = 65, bmi = 30, fpg = 6)
print(result)
- 测试调用R
python3 /home/python/test_rscript.py
- /home/python/test_rest.py
#!usr/bin/env python3
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello FastAPI"}
- 测试Rest接口
cd /home/python && nohup uvicorn resttest:app --reload --host 0.0.0.0 --port 8888 > log.txt 2>&1 &
http://192.168.1.6:8888/
四、提供Rest接口
- qdiabetes.R
# script.R
library(QDiabetes)
- /home/python/qdiabetes .py
from fastapi import FastAPI
from pydantic import BaseModel
import rpy2.robjects as ro
app = FastAPI()
class ItemModel(BaseModel):
type: str
sex: str
age: int
bmi: float
ethn: str
smoke: str
fpg: float
hba1c: float
ro.r('source("/home/rscript/qdiabetes.R")')
@app.post("/qdiabetes")
async def find_qdiabetes(item: ItemModel):
try:
if item.type == "A":
result = ro.r['QDR2018A'](sex=item.sex, age=item.age, bmi=item.bmi, ethn=item.ethn, smoke=item.smoke)
if item.type == "B":
result = ro.r['QDR2018B'](sex=item.sex, age=item.age, bmi=item.bmi, ethn=item.ethn, smoke=item.smoke, fpg=item.fpg)
if item.type == "C":
result = ro.r['QDR2018C'](sex=item.sex, age=item.age, bmi=item.bmi, ethn=item.ethn, smoke=item.smoke, hba1c=item.hba1c)
print(result[0])
return {"type": item.type, "score": result[0]}
except Exception as e:
print(e.args)
return {"error": e.args[0]}
- 启动
cd /home/python && nohup uvicorn qdiabetes:app --reload --host 0.0.0.0 --port 8888 > log.txt 2>&1 &
- 例子