错误:调用Flask API时(Json Decodeerror)

时间:2018-03-16 09:08:36

标签: python rest flask flask-restful

您好我是将Ml模型暴露为烧瓶API的新手。以下是我的代码:

return response()->download($pathToFile);

使用以下代码我调用API:

import numpy as np
from nltk.corpus import wordnet
from nltk.stem.wordnet import WordNetLemmatizer
import re
from sklearn.externals import joblib
import warnings

warnings.filterwarnings('ignore')
from flask import Flask, jsonify, request


app = Flask(__name__)

@app.route("/glcoding", methods=['POST'])    
def mylemmatize(token):
    lmtzr = WordNetLemmatizer()
    lemmas = {}
    lemma = None
    if not token in lemmas:
         lemma = wordnet.morphy(token)

    if not lemma:

         lemma = token

    if lemma == token:
         lemma = lmtzr.lemmatize(token)

    lemmas[token] = lemma

    return lemmas[token]




def cleanmytext(text):
   words = map(mylemmatize,text.lower().split())
   return ' '.join(words)



def glcoding():
    if request.method == 'POST':
         json_data = request.get_json()         
         data = pd.read_json(json_data, orient='index') 

         data['Invoice line item description'] = data['Invoice line item description'].apply(cleanmytext)

    return jsonify(data)

if __name__ == '__main__':
     app.run()

我收到如下所述的错误:

from flask import Flask, jsonify, request
import requests, json



 BASE_URL = "http://127.0.0.1:5000"

  data = '{"0":{"Vendor Number": "166587","Invoice line item description":"Petrol charges with electricity"}}'

  response = requests.post("{}/glcoding".format(BASE_URL), json = data)

  response.json()

当我没有将它作为API公开时,上面的代码工作正常。但是只有在从API调用时才会抛出错误。请帮忙

2 个答案:

答案 0 :(得分:2)

您使用app.route()装饰器修饰了错误的方法。只需将装饰器移到glcoding()方法之上,一切都应该正常工作。

答案 1 :(得分:0)

您定义了请求处理程序mylemmatize(token)以获取名为token的变量,但您路由不知道这一点,因此不会将数据传递给请求处理程序。 改变您的路线:

@app.route("/glcoding", methods=['POST'])

改为:

@app.route("/glcoding/<token>", methods=['POST'])

有关详细信息,请参阅doc on variable rule

此外,如果您不需要将令牌作为变量传递,那么您需要 从mylemmatize函数定义中删除它。