【问题标题】:Error: While calling Flask API (Json Decodeerror)错误:调用 Flask API 时(Json 解码错误)
【发布时间】:2018-03-16 18:14:48
【问题描述】:

您好,我不熟悉将 Ml 模型公开为烧瓶 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()

我正在使用以下代码调用 API:

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()

我收到如下所述的错误:

Traceback (most recent call last):
  TypeError: mylemmatize() takes exactly 1 argument (0 given)
    127.0.0.1 - - [16/Mar/2018 14:31:51] "POST /glcoding HTTP/1.1" 500 -

当我不将上面的代码作为 API 公开时,它可以正常工作。但只有在从 API 调用时才会引发错误。请帮忙

【问题讨论】:

  • 请修正您的代码缩进。
  • @brunodesthuilliers 我的错误编辑了代码缩进

标签: python rest flask flask-restful


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    改为:

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

    请参阅doc on variable rule 了解更多信息。

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

    【讨论】:

    • 实际上,如果您阅读整个代码 sn-p 似乎 sewi 的答案是正确的......
    • 是的,没错。我只查看了错误似乎来自的第一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2013-08-14
    相关资源
    最近更新 更多