从烧瓶请求Python获取空

时间:2018-10-25 08:12:52

标签: python flask null

我正在编写一个简单的flask应用程序,根据我的查询,我应该以所需的格式获得所需的答案。 代码如下;

#-*- coding: utf-8 -*-
import StringIO
import os
import pandas as pd
import numpy as np
from flask import Flask, request, Response, abort, jsonify, send_from_directory,make_response
import io
from pandas import DataFrame
import urllib2, json
import requests
from flask import session
import sys  


reload(sys)  
sys.setdefaultencoding("ISO-8859-1")
app = Flask(__name__)

@app.route("/api/conversation/", methods=['POST'])
def chatbot():
    df = pd.DataFrame(json.load(urllib2.urlopen('http://192.168.21.245/sixthsensedata/server/Test_new.json')))
    question = request.form.get('question')
    store = []

    if question == 'What is the number of total observation of the dataset':
       store.append(df.shape)

    if question == 'What are the column names of the dataset':
       store.append(df.columns)
    return jsonify(store)

if __name__ == '__main__':
    app.debug = True
    app.run(host = '192.168.21.11',port=5000)

它运行正常,但响应为空。我想再创建约30个这样的问题,并将值存储在store数组中。但是,我认为值没有被附加到store内。

不过,在jupyter笔记本中,我得到了适当的答复;

df = pd.DataFrame(json.load(urllib2.urlopen('http://192.168.21.245/sixthsensedata/server/Test_new.json')))
store = []
store.append(df.shape)
print store
[(521, 24)]

为什么在烧瓶中没有附加值?我正在邮递员中测试我的应用程序。请指导我缺少的地方。

邮递员截屏enter image description here

1 个答案:

答案 0 :(得分:1)

不提供Post方法的数据类型时,request.form的计算结果为

ImmutableMultiDict([('{"question": "What is the number of total observation of the dataset"}', u'')])

question = request.form.get('question')最终都不是 您可以显式使用内容类型作为json,或强制加载它。

@app.route('/api/conversation/', methods=['POST'])
def chatbot():
    question = request.get_json(force=True).get('question')
    store = []

    if question == 'What is the number of total observation of the dataset':
        store.append("shape")
    elif question == 'What are the column names of the dataset':
        store.append("columns")
    return jsonify(store)

卷曲请求

$curl -X POST -d '{"question": "What is the number of total observation of the dataset"}' http://127.0.0.1:5000/api/conversation/

[“形状”]

$curl -H 'Content-Type: application/json' -X POST -d '{"question": "What is the number of total observation of the dataset"}' http://127.0.0.1:5000/api/conversation/

[“形状”]