通过flask中的请求args访问url参数

时间:2018-06-14 11:41:02

标签: flask

我一直试图通过烧瓶部署机器学习模型。我需要通过url传递一些文本,以便可以检索它以进行分类。我正在使用request.args.get函数,但它抛出错误:

TypeError: index() got an unexpected keyword argument 'text'

网址是:

http://127.0.0.1:8000/index/text=Windows%20is%20a%20operating%20system

它也显示错误:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

service.py:

from flask import Flask, request, jsonify
import pickle

app = Flask(__name__)

file = open("models/GridSearchCV_nb.pickle","rb")
nb_clf = pickle.load(file)

file = open("models/GridSearchCV_svm.pickle","rb")
svc_clf = pickle.load(file)

file = open("models/ctargets.pickle","rb")
targets = pickle.load(file)

def nbclassifyit(text):
  idx_nb = nb_clf.predict([text])[0]
  return targets[idx_nb]

def svclassifyit(text):
  idx_svc = svc_clf.predict([text])[0]
  return targets[idx_svc]


@app.route('/index/<text>')
def index():
 text = request.args.get('text')
 result = {"prediction" : nbclassifyit(text)}
 return jsonify(result)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

request.args.get函数在路径末尾的?之后查找参数。您不需要在路线中使用<text>

因此您可以尝试更改索引路径和功能,如下所示:

@app.route('/index/')
def index():
 text = request.args.get('text')
 result = {"prediction" : nbclassifyit(text)}
 return jsonify(result)

并在您的网址中提供文字参数:

http://127.0.0.1:8000/index/?text=Windows%20is%20a%20operating%20system