Flask framework, how to use ajax to refresh value - javascript

I'm a new with flask and now I need to makes my page dynamic.
That's why I'm trying to send data from JS to Python using the JSON format with AJAX but surfing the web I can't understand how to do it.
Can anyone show me a simple implementation of how AJAX is used on Flask to change the value of a variable every X time?
This my flask app:
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify, make_response
app = Flask(__name__)
#app.route("/getdata", methods = ['POST', 'GET'])
def getdata():
#get JSON data and change it
return data
#app.route("/data")
def data():
# show dynamically the data
return render_template("data.html")
if __name__ == "__main__":
app.run(debug=True, port=5000)
This is my js function, the gauge array is the value to make dynamic
setInterval(
ciccio.refreshValue({{gauge[0]}})
,wrapper.refreshValue({{gauge[1]}})
,wrapper1.refreshValue({{gauge[2]}})
,wrapper2.refreshValue({{gauge[3]}})
,wrapper3.refreshValue({{gauge[4]}})
,wrapper4.refreshValue({{gauge[5]}})
,wrapper5.refreshValue({{gauge[6]}})
,wrapper6.refreshValue({{gauge[7]}})
,500);
)
I need to refresh the gauge array

I have resolved by this code
python:
def getdata():
return jsonify({'results' : sample(range(101), 2)}) # some data from the server
#app.route("/misuratore")
def data():
return render_template("misuratore.html")
javascript
setInterval(
function updateGauge() {
var updatedData = $.get('/getdata'); //get data from localhost/getdata
updatedData.done(function(results) { // when the get are completed launch function that apply the new value
pippo.refreshValue(results.results[0])
pluto.refreshValue(results.results[1])
});
},1000); // every second

Related

How to send user specific data using SSE

i am trying to create a social media page where in home page of every user they can see feeds,
feeds from friend's post. when ever my friend create a post i can see the same in my feeds in real time.
For that i am using SSE in python flask. everything working find but after adding few more users only i realise all the post are coming to all logged in people's feed. which wrong, i want to see feeds from only my friends.
Can any one help me how to achieve it. i am sharing the base level code of python and java script.
Client side:
var source = new EventSource("http://172.19.0.3:8044/events");
source.addEventListener('user_feeds', function(event) {
var data = JSON.parse(event.data);
console.log("Even from server ");
console.log(data);
}, false);
Server side
from flask_cors import CORS
from flask_sse import sse
from factory import create_app
app = create_app()
CORS(app)
app.config["REDIS_URL"] = "redis://redis"
input_user_feeds = dict()
app.register_blueprint(sse, url_prefix='/events)
PROMOTION_BLUEPRINT = Blueprint('my_page', __name__, url_prefix='/api/v1/')
#PROMOTION_BLUEPRINT.route('/feeds/<user_id>', methods=["GET"])
def feeds(user_id):
push_feeds(user_id)
return "SUCCESS"
#PROMOTION_BLUEPRINT.route('/user_request/<user_id>', methods=["POST"])
def user_request(user_id):
data = request.json
add_feeds(user_id, data)
return "SUCESS"
def push_feeds(user_id):
while 1 == 1:
if user_id in input_user_feeds:
input_request = input_user_feeds[user_id]
sse.publish(input_request, type='user_feeds')
del input_user_feeds[user_id]
def add_feeds(user_id, data):
input_user_feeds[user_id] = data
if __name__ == '__main__':
app.run(host='0.0.0.0', port=Config.PORT, debug=True)
I trued to do with single user id. but that is also not a good idea.
It will be helpful if anyone having good knowledge in SSE help me find the solution.
Thanks in advance.

Python Flask and JQuery.post Are Not Working Together

I am creating a very simple dashboard for automating a task.
Security is not a concern here because I am only local hosting.
JQuery Code
$.post("/approve", data={"title":title,"content":content}, success=function(){
window.location.reload(true)
});
Flask Code
#app.post('/approve')
def approve_topic():
args = request.args
print(args)
json.dump(args, open("topics/"+uuid4().hex+".json", "w"))
return {"status":"clear"}
Result (the JSON file)
{}
Expected Result
{"title":"whatever the title is", "content":"whatever the content is"}
Any idea why this is happening?
The first time I ran this it worked just fine, but now no matter what I reset or what I do it won't work.
I just tested the code, it is working fine with request.form.
Flask Code:
from flask import Flask, request
app = Flask(__name__)
# you can ignore this function as you're doing request on same origin
#app.after_request
def allow_cors_origin(response):
"""Resolve CORS error"""
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS")
return response
#app.route("/echo", methods=["POST"])
def echo():
data = request.form
print(data) # Output: ImmutableMultiDict([('a', '1')])
return data
app.run(debug=True)
jQuery Code:
$.post("http://localhost:5000/echo", {a: 1}, r=>console.log("response: ", r))
// Output: response: {a: '1'}

Flask socketio not receiving any message from javascript even after the connection is established

I am trying to get response from javascript after the connection is established between the flask and javascript.The onconnect() function is working properly but onmessage() is not.
I tried broadcast along with the emit method in javascript too but it's not working.
This is my app.py
app=Flask(__name__)
bootstrap=Bootstrap(app)
socketio=SocketIO(app)
app.config['SECRET_KEY']="MY_KEY"
#app.route('/')
def login():
return render_template('index.html')
#app.route('/home',methods=['GET','POST'])
def home():
if(request.method=='POST'):
data=request.form
name=data['name']
return render_template('message.html',name=name)
else:
return render_template('index.html')
#socketio.on('connect')
def onconnect():
print("connect")
#socketio.on('message')
def onmessage(message):
print('message')
if(__name__=='__main__'):
socketio.run(app)
and this is my javascript file
const ws =io.connect(window.location.href)
ws.on('connect', function() {
console.log("Connection estalished")
ws.emit("adsd",broadcast=true)
});
EDIT:
There is a mistake in the javscript.
const ws =io()
This should be used for establishing the connection , not the previous method.
My Project is completed.
Link for the github project
First of all, only the server can broadcast, clients can only emit to the server.
Second, you are emitting an event named adsd, so you need to add a handler for that event in your server. For example:
#socketio.on('adsd')
def adsd_handler():
print('got adsd!')

API works in Postman, but not on a browser

I created a flask api connecting to my mongodb database.
My initial part of the code looks like:
app = Flask(__name__)
cors = CORS(app, resources={
r"/api/v1/*": {"origin": "*"},
})
client = MongoClient(connection_str)
db = client.get_database(db_name)
#app.route("/api/v1/players", methods = ['GET'])
def get_all_players():
....
This works as I intended when I use Postman, but when I input directly into the browser (localhost:5000/api/v1/players), it shows me an error as follows:
I think this is the reason why my fetch doesn't work.
Any thoughts?
It's the problem with SSL certificate. All you need to do, is add ssl_context='adhoc' to your app.run() call.
An example :
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello"
if __name__ == "__main__":
app.run(ssl_context='adhoc')
also you need to install pyopenssl in your virtual environment

how can I get variable from javascript using flask

So I have set up app.py, index.js, index.html in appropriate folder as flask suggests. Index.html gets rendered as when app.py runs then index.html runs index.js which grabs input data from user. I am trying to send this input and send it to python where I can call an API, grab data, and work with it however I cannot think of a way to do this.
my app.py:
import os
from flask import Flask, render_template, jsonify, request, redirect
app = Flask(__name__)
# This will run upon entrance
#app.route("/")
def home():
return render_template("index.html")
#app.route("/stock_data")
def get_stock_data():
# called from index.js Plot function
if __name__ == "__main__":
app.run()
and here is my javascript code:
console.log("everythin works fine.")
d3.select("#stocklabelsubmit").on("click", submitted)
function submitted(){
d3.event.preventDefault();
// grab label inputted.
var inputted_label = d3.select("#stockInput").node().value;
d3.select("#stockInput").node().value = "";
Plot(inputted_label);
};
function Plot(input){
var url = "full url"
// when this function is called call /stock_data function!!
// data is what is returned from python
d3.json(url).then(function(data){
})
}
Everything works fine, when I console log inputted_label at the end of function submitted it works. Now I want to send inputted_label variable to /stock_data. Thanks in advance!
var url = "/stock_data"
This needs to be a valid URL, not just the path to the Flask endpoint. That means it must start with "http://" or "https://" and include a domain. For development purposes, "http://localhost/stock_data" will work. If you ever deploy this to a server, you will want to create a configuration file so that the host name can be configured depending on what environment you are running in.

Categories

Resources