简体   繁体   中英

Getting null from flask request python

I am writing a simple flask application where based on my query, I should get the required answer in the desired format. The code is as below;

#-*- 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)

It's running properly but getting null response. I would like to create ~30 more questions like this & store values in the store array. But values are not getting appended inside store , I think.

In jupyter notebook, though, I am getting proper response;

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

Why in flask, the values are not getting appended? I am testing my application in postman. Please guide where I am lacking.

Screenshot from postman 在此处输入图片说明

When not providing the data type for the Post method, request.form evaluates to

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

and question = request.form.get('question') ends up being none You can explicitly use content type as json, or force load it.

@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 requests

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

["shape"]

$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/

["shape"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM