簡體   English   中英

Flask:函數未返回任何字符串並收到內部服務器錯誤 500

[英]Flask: Function is not returning any String and getting Internal Server Error 500

我正在使用 Flask RESTful API 向前端返回一堆字符串。 該字符串是在 ML 算法對輸入字符串運行並將其分類為預定義的答案之后生成的。 后端在 MongoDB 中。

下面給出的代碼之前工作正常。 自從我插入了以下幾行(標記為 *)后,它就沒有返回任何值。 調試后我發現錯誤為built-in error: The view function could not return a list

以下是我的代碼(僅相關部分)

app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/response/',methods = ['GET','POST'])
def response():       

    if request.method=='POST':
        text_org = request.json['foo']
        text = json.loads(json.dumps(text_org))
        text = text.lower()
        if len(text.split())==0:
            return 'Please ask a question'
        elif len(text.split())<=3:
            resp = ' '.join(['What more would you like to know about', clean_text(text), '? Please be little more specific..']) 
            return resp
        else:
            df_to_match = pd.DataFrame({'Slot_Value':tbl_df['slot_value'],'User_In':[clean_text(text)]*len(tbl_df['slot_value'])})
            is_match = [process.extract(i, df_to_match['Slot_Value'], limit=3) for i in df_to_match['User_In']]
            is_match_ratio = [i for w in is_match for i in w]
            if list(is_match_ratio[0]).pop(1) > 65:
                #tup = [w for (w,i,n) in is_match_ratio]
                x = model.predict([text])
                x_t = le.inverse_transform(x) '# *new line
                x_t = x_t.tolist() '# *new line
                x_f = ' '.join(x_t)
                x_f = re.sub('[^A-Za-z0-9,]',' ',x_f)  # * new line
                y=x_f.replace(' ','').split(',')
                slot_value tbl_df.loc[tbl_df.Combi.str.contains(y),'slot_value']
                text_clean = clean_text(text) #User Defined Function for Text preprocessing
                df_exact = pd.DataFrame({'Slot_Value':slot_value,'User_input':[text_clean]*len(slot_value)})
                slot_exact = [process.extract(i, df_exact['Slot_Value'], limit=1) for i in df_exact['User_input']]
                slot_exact = ' '.join([n[0] for n in slot_exact[0]])
                for i in db_col.find({"slot_value":slot_exact},{"Answer":1,"_id":0}): # querying mongodb with only 'Answer' shall be retrieved
                    m = json.dumps(i).split('Answer',1)[-1] 
                    resp = m.replace('\\n','<br>').replace('"','').replace(':','').replace('}','')
                    resp_final = email_url(resp) # * new line
                    return resp_final
            else:
                resp = ' '.join(['Sorry I have not understood this, please rephrase the question or'])
                return resp
    else:
        resp = [random.choices(msg)]
        return resp



if __name__ == "__main__":
    print("**Starting Server...")

app.run(host='0.0.0.0',port=5002, debug=True)

email_url是一個 UDF,它執行一些正則表達式並返回帶有 HTML 標簽的變量resp 我發現所有像text.split()<=3 , ' '.join(['Sorry I have not understood ..... '])這樣的特殊情況都可以正常工作。 所以這意味着問題出在標有 * 的新行上,可能是我遺漏了什么?

編輯:更多信息

le: LabelEncoder model: MultinomialNB()

上述模型用於預測通過text_org = request.json['foo']接收到的新輸入的類別

我得到了解決方案。 我在下面的行

slot_value tbl_df.loc[tbl_df.Combi.str.contains(y),'slot_value']

而不是y這是一個list ,我已將其更改為','.join(y)

啟發他人: le.inverse_transform總是生成一個需要轉換為列表的數組。 在上面的代碼片段中, y就是那個列表。 因此發生了這樣的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM