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"]
Related
I'm trying to create new lines using python for the variable "profile" using the 'new_line' variable, but I haven't been successful.
The code below does not produce errors. It gives me all 3 strings in one line and I'd like to get 3 lines.
I would like the output to look like this with a new line for each string.
response: response
Lat/Lon: 1293.2312,123123.432
City: New York"
from flask import Flask
from flask import jsonify
import requests
import json
import os
app = Flask(__name__)
#app.route('/change/')
def he():
API_KEY = "API_KEY"
CITY_NAME = "oakland"
url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={API_KEY}"
response = requests.get(url).json()
new_line='\n'
profile = (
f"response: {response} ============== {new_line}"
f"Lat/Lon: {response['coord']} ========={new_line}"
f"City: {CITY_NAME}========{new_line}"
)
return profile
Try new_line='</br>'.
If you're viewing it in browser, it may interpret the page as badly formatted HTML and ignore line breaks and whitespaces, therefore you will need to use tags for that.
I created a chatbot using for loop.In browser it is not giving response when user enters the text.
I tried like below:
app.py:
import flask
from flask import Flask, render_template, request
from werkzeug.wrappers import Request, Response
import pandas as pd
import re
#####***** Reading the data
data=pd.read_excel("path",sheet_name='Sheet2')
#######**** Converting columns to a lists
userList=data["User"].tolist()
cbList=data["CB"].tolist()
app = Flask(__name__)
##########***** asking user to enter their questions and giving responses
bot_response=[]
for i in range(0,len(userList)):
user=input("User:")
if user=='':
print("Bye")
break
userReg=re.sub('[^A-Za-z0-9]'," ",user.lower())
userRegSplit=(userReg.split())
ud=str(userList[i]).lower()
ud=re.sub('[^A-Za-z0-9]'," ",ud)
newList=ud.split()
commonWords=[x for x in newList if x in userRegSplit]
if len(commonWords)==len(newList):
bot_response.append(cbList[i])
print(bot_response)
#app.route('/')
def CBApp():
return render_template('CBApp.html')
#app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
return str(bot_response.get_response(userText))
if __name__=='__main__':
from werkzeug.serving import run_simple
app.debug=True
run_simple('localhost',port,app)
html template will look like below:
[1]: https://i.stack.imgur.com/rY4tW.png
suggest me where am gone wrong?
Now, I managed to successfully pull basic information from my smart device onto the terminal using pyHS100 on python (v3.6) using the following code
from pyHS100 import SmartPlug
from pprint import pformat as pf
plug = SmartPlug("10.xxx.xxx.xxx")
print("Hardware: %s" % pf(plug.hw_info))
which results in the following:
but I can't parse the data into json format and display it on the local server for my RESTful API purpose if I done it this way:
from flask import Flask, jsonify
from flask_restful import Resource, Api
from pyHS100 import SmartPlug
app = Flask(__name__)
#app.route('/api')
def get():
plug = SmartPlug("10.xxx.xxx.xxx")
sys = plug.hw_info
return jsonify({'data':sys})
if __name__ == '__main__':
app.run(host='0.0.0.0')
app.run(debug=True)
All I need is for the information to be presented into something like this:
What did I do wrong and how do I this fix? Thanks
I believe the best way to solving this is by using json.dumps
I am trying to create a machine Learning application with Flask. I have created a POST API route that will take the data and transform it into a pandas dataframe. Here is the Flask code that calls the python function to transform the data.
from flask import Flask, abort, request
import json
import mlFlask as ml
import pandas as pd
app = Flask(__name__)
#app.route('/test', methods=['POST'])
def test():
if not request.json:
abort(400)
print type(request.json)
result = ml.classification(request.json)
return json.dumps(result)
This is the file that contains the helper function.
def jsonToDataFrame(data):
print type(data)
df = pd.DataFrame.from_dict(data,orient='columns')
But I am getting an import error. Also, when I print the type of data is dict so I don't know why it would cause an issue. It works when I orient the dataframe based on index but it doesn't work based on column.
ValueError: If using all scalar values, you must pass an index
Here is the body of the request in JSON format.
{
"updatedDate":"2012-09-30T23:51:45.778Z",
"createdDate":"2012-09-30T23:51:45.778Z",
"date":"2012-06-30T00:00:00.000Z",
"name":"Mad Max",
"Type":"SBC",
"Org":"Private",
"month":"Feb"
}
What am I doing wrong here ?
I'm parsing JSON data in Flask from POST request. Everything seems to be fine and works ok:
from flask import Flask
from flask import request
import io
import json
import pandas as pd
app = Flask(__name__)
#app.route('/postjson', methods = ['POST'])
def postJsonHandler():
print (request.is_json)
content = request.get_json()
df = pd.io.json.json_normalize(content)
print (df)
return 'JSON posted'
app.run(host='0.0.0.0', port= 8090)
The output looks like this:
True
columns data
0 [Days, Orders] [[10/1/16, 284], [10/2/16, 633], [10/3/16, 532...
Then I try to transform json to pandas dataframe using json_normalize() function. So I receiving the result close to pandas dataframe but it is not yet it.
What changes in the code should I do to receive classical Pandas Dataframe format with columns and data inside.
Thanks in advance.
Solved the problem. The idea was to use parameters of the json_normalize() function something like that:
df = pd.io.json.json_normalize(content, 'data')