【问题标题】:Access variable and render it in different URL访问变量并在不同的 URL 中呈现它
【发布时间】:2018-04-18 06:42:17
【问题描述】:

我尝试在 url('/hello') 上的 URL(/predict) 中呈现变量('predictions')。我是网络开发的初学者。如果有人知道,请帮忙。

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def apicall(responses = None):

    test_json = request.get_json()

    test = pd.read_json(test_json, orient='records')

    query_df = pd.DataFrame(test)

    clf = 'kmeans__model.pkl'

    print("Loading the model...")
    lin_reg_model = None
    with open(clf,'rb') as f:

        lin_reg_model = joblib.load(f)

        # lin_reg_model = joblib.load('/home/q/new_project/models/kmeans_model.pkl')

        print("The model has been loaded...doing predictions now...")

        predictions = lin_reg_model.predict(test)

        print(predictions)


        prediction_series = list(pd.Series(predictions))

        final_predictions = pd.DataFrame(list(zip(prediction_series)))

        responses = jsonify(predictions=final_predictions.to_json(orient="records"))
        responses.status_code = 200

        return (responses)

@app.route('/hello')

def hello():

  **What should be used here to render *predictions*?**  

    return 'Hello, World '

【问题讨论】:

  • hello url执行时是否要运行apicall函数?
  • 是的,我也想在 hello url 中打印名为“predictions”的变量。是否可以在预测 u​​rl 中呈现此变量?
  • 是什么阻止了您不通过烧瓶路由调用类似 apicall() 的函数。
  • 是否可以在predict url中渲染这个变量?
  • 我还是不明白。得到预测后,您想在模板中显示吗?

标签: machine-learning flask web-deployment


【解决方案1】:

如果您愿意,您可以返回模板并以 html 显示。创建 templates 文件夹并创建 html 文件。

import requests

def hello():
    response = requests.get(url_for('apicall'))
    return render_template('<yourtemplate.html>', predictions=response.json())

HTML

{{ predictions }}

注意:有关线程和部署的任何问题请点击此链接Handling multiple requests in Flask

【讨论】:

  • 问题是函数 hello 看不到变量“预测”。
  • 127.0.0.1:8000/predict。我收到此错误“方法不允许 请求的 URL 不允许该方法”
  • 请在方法中添加 GET
  • 您还必须添加预测变量。我以为你可以调用预测并分配给预测变量
  • 查看我的编辑也请从 apicall 中删除 app.route 装饰器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
  • 2011-12-21
相关资源
最近更新 更多