Flask API退出后无法找到自己的路径?

时间:2015-10-20 17:33:50

标签: python r flask

关于这个问题:

我写了一个简单的烧瓶api来提供我正在研究的各种分类器的结果(一些在python中,一些在R中)。我试图通过rpy2与R中的那个接口,并通过Flask api返回结果。

以下是代码:

from flask import Flask, json, request, jsonify
app = Flask(__name__)
#import salary_api
from run_model import classify_vector, vectorize
import rpy2.robjects as robjects
import sys
import os
from rpy2.robjects.packages import STAP
model = os.path.join('model', 'StandaloneFns.R')
with open(model, 'r') as f:
    string = f.read()
    model = STAP(string, "model")


@app.route('/')
def index():
    return "Welcome to to the application."

@app.route('/classify/')
def classify():
    print "got request"
    data = request.json
    print "data:", data
    result = classify_vector(vectorize(data))
    try:
        return jsonify({'result': result[0]})
    except IndexError:
        return jsonify({})

@app.route('/price_estimate/')
def estimate():
    print "request received"
    data = request.json
    print "data:", data

robjects.r('''setwd("/home/name/fetcher/productionized/model")
# Load Sample data
load("datz1.Rd")
# Load Parameters
load("gmcfs.Rd")
# Load Mean utils (for Shrinkage)
load("allab.Rd")

# Retained Variables from ENet
vars=c("job_state","company_type","hascomm","company_declared_job_slots_needed","job_total_benefits","employment_type","is_resume_required",
"job_medical_benefit","job_vision_benefit","job_dental_benefit","job_life_insurance_benefit","job_category") 
frm = ~job_state*prc+company_type*prc+hascomm*prc+company_declared_job_slots_needed*prc+job_total_benefits*prc+employment_type*prc+is_resume_required*prc+job_medical_benefit*prc+job_vision_benefit*prc+job_dental_benefit*prc+job_life_insurance_benefit*prc+job_category*prc-1
modm= (model.matrix(frm,data=tdz1))  
levs = lapply(datz2, levels)
c1 = attributes(modm)$contrasts

# Transform to factors as needed
datz2 = datz1
for(v in vars) if(typeof(datz2[,v])=="character") datz2[,v] = as.factor(datz2[,v])''')
    data_r = robjects.DataFrame(result[0])
    print "converted object to dataframe"
    data_factored = model.prepdata(data_r)
    print "factored request"
    result = model.targp(data_factored)
    print "modeled request"
try:
    return jsonify({'price': result[0]})
except IndexError:
    return jsonify({})

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

当我运行此api时,我从终端收到以下消息:

name@compname-ThinkPad-T440p:~/fetcher/productionized$ python api.py
Importing vectorizer...
Importing model...
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
/usr/bin/python: can't open file 'api.py': [Errno 2] No such file or directory

这对我来说毫无意义。它运行正常,然后断开连接,无法找到自己。任何人都知道这里发生了什么?

1 个答案:

答案 0 :(得分:0)

代码中的某些内容会更改工作目录。您可以使用以下最小示例轻松重现此错误:

from flask import Flask
import os

app = Flask(__name__)

os.chdir('sampledir')

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True) 

当我运行此应用时:

$ ./venv/bin/python app.py 
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
/path/to/venv/bin/python: can't open file 'app.py': [Errno 2] No such file or directory

尝试在代码中找到os.chdir()来电和其他人。