I'm setting up an API using Flask, and add some JSON post using postman to be transferred to mongoDB database.
Then I had to visualize statistics of the real time data from the database into lets say data_analysis_script.py, which means if I post some JSON from postman, the statistics should be changed since the data had been added.
Any suggestion about function or library I could use further in script for showing the data statistics ?
I had tried using manager which could run both app.run() and the code, but not print the code
API code
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo
import pandas as pd
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'db'
app.config['MONGO_URI'] = 'mongodb://localhost:8000/db'
mongo = PyMongo(app)
#app.route('/stocks', methods=['GET'])
def get_all_stocks():
stocks = mongo.db.stocks
output = []
for i in stocks.find():
output.append({'name' : i['name'], 'item' : i['item']})
return jsonify({'Here yours' : output})
#app.route('/add', methods=['POST'])
def add_stocks():
stocks = mongo.db.stocks
name = request.json['name']
item = request.json['item']
item_id = stocks.insert({'name': name, 'item': item})
new_stocks = stocks.find_one({'_id': stocks_id })
output = {'name' : new_stocks['name'], 'item' : new_stocks['item']}
return jsonify({'Here yours' : output})
#app.route('/stocks/', methods=['GET'])
def get_one_stocks(name):
stocks = mongo.db.stocks
c = stocks.find_one({'name' : name})
if s:
output = {'name' : c['name'], 'item' : c['item']}
else:
output = "Nothing"
return jsonify({'Here yours' : output})
if __name__ == '__main__':
app.run(debug=True)
I expect the data visualization and statistics changed when there is a JSON entry
Related
i have a problem with my flask app thaht i'm trying to create,
i wrote a POST Method to take arguments from HTTP and write them to a table.
here's my code:
from flask import Flask
from flask_restful import Resource, Api, reqparse
import pandas as pd
import ast
import sqlalchemy
# SQLAlchemy connectable
engine = sqlalchemy.create_engine("mssql+pymssql://my_connection_string")
conn = engine.connect()
app = Flask(__name__)
api = Api(app)
class Samples(Resource):
def get(self):
data = pd.read_sql_table('DBLIST_DATA', engine)
data = data.to_dict() # convert dataframe to dict
return {'data': data}, 200 # return data and 200 OK
def post(self):
parser = reqparse.RequestParser() # initialize
parser.add_argument('NODE_NO_data', required=True) # add args
parser.add_argument('BLOCK_NAME_data', required=True)
parser.add_argument('BLOCK_TYPE_data', required=True)
args = parser.parse_args() # parse arguments to dictionary
# read our SQL Table
data = pd.read_sql_table('DBLIST_DATA', engine)
#Check if Value Exists
if args['NODE_NO_data'] in list(data['NODE_NO_data']):
return {
'message': f"'{args['NODE_NO_data']}' already exists."
}, 409
else:
# create new dataframe containing new values
new_data = pd.DataFrame({
'NODE_NO_data': [args['NODE_NO_data']],
'BLOCK_NAME_data': [args['BLOCK_NAME_data']],
'BLOCK_TYPE_data': [args['BLOCK_TYPE_data']],
'locations': [[]]
})
# add the newly provided values
data = data.append(new_data, ignore_index=True)
data.to_sql('DBLIST_DATA', index=False) # save back to SQL Table
return {'data': data.to_dict()}, 200 # return data with 200 OK
api.add_resource(Samples, '/samples') # add endpoints
if __name__ == '__main__':
app.run() # run app
when i try to POST via Postman the following values:
127.0.0.1:5000/samples/?NODE_NO_data=1&BLOCK_NAME_data=Machine&BLOCK_TYPE_data=Vertical
i'm getting a 404 not found error.
can someone please tell me what i'm doing wrong?
Thanks!
You could just remove the last / of your request URL http://127.0.0.1:5000/samples.
length of the password must be at least 6 characters while signing up using Dialogflow chatbot.
I have used system entity "any". But it is so generalized.
Webhook is written in flask python.
Also tried to do it by using [0-9]{6}$ as a regex entity. But unable to find a proper way to perform this task.
from dialogflow_fulfillment import QuickReplies, WebhookClient, Payload
from flask import Flask, request, Response, jsonify , make_response
import json
import requests
app = Flask(__name__)
def handler(agent: WebhookClient) :
"""Handle the webhook request.."""
req = request.get_json(force=True)
intent_name = req.get('queryResult').get('intent').get('displayName')
if intent_name == 'intro':
agent.add('I am the chatbot of this page. Ready to assist you with anything you need. What would you like to do?')
agent.add(QuickReplies(quick_replies=['START NOW','LOGIN']))
if intent_name == 'get_started':
url = 'http://**********.com/create_account'
userid = req.get('queryResult').get('parameters').get('email')
print(userid)
pwd = req.get('queryResult').get('parameters').get('pwd')
print(pwd)
name = req.get('queryResult').get('parameters').get('person')['name']
print(name)
age = req.get('queryResult').get('parameters').get('age')
print(age)
myobj = {'userid': userid, 'pwd': pwd , 'name' : name, 'age' : age}
x = requests.post(url, data = myobj)
result=x.text
agent.add(result)
if intent_name == 'login_screen' :
url = 'http://**********.com/auth_account'
userid = req.get('queryResult').get('parameters').get('email')
print(userid)
pwd = req.get('queryResult').get('parameters').get('pwd')
print(pwd)
myobj = {'userid': userid, 'pwd': pwd }
x = requests.post(url, data = myobj)
result = x.text
agent.add(result)
#app.route('/webhook', methods=['GET', 'POST'])
def webhook():
"""Handle webhook requests from Dialogflow."""
req = request.get_json(force=True)
agent = WebhookClient(req)
agent.handle_request(handler)
return agent.response
if __name__ == '__main__':
app.run(debug=True)
With regex :
Defined regex :
How to do this properly?
How to use regex in it?
Or should i use another approach?
i created this rest api with flask and sql alchemy and i want to not enter the json data manually but get it from another json and add it to my database :
https://www.habitat.fr/api/qDbBye4V7vtMu8qL97vvHTAnLQuEhC/product/911095/sku
my add product route in flask
#add product
#app.route('/product', methods=['POST'])
def add_product():
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
new_product = Product(name,description,price,qty)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
All you need do is write a function using requests and json modules to fetch the json in the url like this:
import requests
import json
def get_data():
r = requests.get('https://www.habitat.fr/api/qDbBye4V7vtMu8qL97vvHTAnLQuEhC/product/911095/sku')
return json.loads(r.content) #convert content to dict
You may now call the function in your flask app:
#app.route('/product', methods=['POST'])
def add_product():
my_data = get_data()
name = my_data['name']
description = my_data['description']
price = my_data['price']
qty = my_data['qty']
This is the project so far: http://oussama1997.pythonanywhere.com/
Here is the Flask-Python code:
from flask import Flask, render_template, request, url_for, session
import requests
app = Flask(__name__)
country = 'Morocco'
#app.route("/", methods=['GET', 'POST'])
#app.route("/covid", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
global country
new_country = request.form.get('country')
country = new_country
url = "https://coronavirus-19-api.herokuapp.com/countries/{}"
r = requests.get(url.format(country)).json()
covid = {
'country': country.upper(),
'confirmed': r['cases'],
'recovered': r['recovered'],
'critical': r['critical'],
'deaths': r['deaths'],
'todayCases': r['todayCases'],
'todayDeaths': r['todayDeaths'],
'active': r['active'],
'totalTests': r['totalTests'],
}
print(covid)
return render_template("index.html", covid=covid)
#app.route("/protect")
def protect():
return render_template("protect.html")
if __name__ == "__main__":
app.run(debug=True)
now in html I want to make the news ticker but I don't know how to get information from each country individually, for example:
USA: 5498464 | Canada: 5465465 | Spain: 5465654 | Germany: 8765165...
thank you all.
Well currently you are asking the api for data about a given country. This api provides a method for pulling data for all countries which is a GET request to:
https://coronavirus-19-api.herokuapp.com/countries
Using that, you can iterate over the response to build out your desired output like:
r = requests.get('https://coronavirus-19-api.herokuapp.com/countries').json()
for country_data in r
print(country_data.country, country_data.cases)
COVID19 API documentation
First of I'm new to python and flask. I've searched around and tried something things to no avail. I have a model that has a DateTimeField as one of the members, let's call it "created_at". When I go to return the query set as JSON I see this for the field
...
"created_at": {
"$date": 1412938697488
}
...
Is there anyway to get the output, either through a custom JSON encoder, etc to get it to look like this :
"created_at": "2014-10-10T07:33:04Z",
Any guidance or suggestions would be greatly appreciated.
Thanks!
Here is an example using flask and flask-mongoengine to get a date as ISO 8601 string
import datetime
from bson.json_util import dumps
from flask import Flask, Response, request
from flask_mongoengine import MongoEngine
app = Flask(__name__)
db = MongoEngine()
class Movie(db.Document):
name = db.StringField(required=True, unique=True)
casts = db.ListField(db.StringField(), required=True)
genres = db.ListField(db.StringField(), required=True)
created_at = db.DateTimeField(default=datetime.datetime.utcnow)
#app.route('/movies')
def get_movies():
movies = Movie.objects()
movies_list = []
for movie in movies:
movie_dict = movie.to_mongo().to_dict()
movie_dict['created_at'] = movie.created_at.isoformat()
movies_list.append(movie_dict)
movies_josn = dumps(movies_list)
return Response(movies_josn, mimetype="application/json", status=200)
#app.route('/movies', methods=['POST'])
def add_movie():
body = request.get_json()
movie = Movie(**body).save()
id = movie.id
return {'id': str(id)}, 200
if __name__ == '__main__':
app.config['MONGODB_SETTINGS'] = {
'host': 'mongodb://localhost/movie-bag'
}
db.init_app(app)
app.run()