I have a flask application that I am trying to send some json to the browser and render it. But the line with $.getJSON() is not running. The jist of which is below:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index_html():
data = {"this":"is", "just":"a test"}
return render_template('index.html', data=data)
if __name__ == '__main__':
app.run(debug=True)
index.html
<html>
<head>
<script src="{{url_for('static', filename='jquery-3.5.1.min.js')}}"></script>
<script src="{{url_for('static', filename='leaflet/leaflet.js')}}"></script>
<link rel="stylesheet" href="{{url_for('static', filename='leaflet/leaflet.css')}}">
<link rel="stylesheet" href="{{url_for('static', filename='app.css')}}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<h1>My test that doesn't work</h1>
<div id="llmap"></div>
<script src="{{url_for('static', filename='app.js')}}"></script>
</body>
app.js
console.log("before")
$.getJSON("/", function(data){
console.log("during")
console.log(JSON.stringify(data));
});
console.log('after')
Console OUTPUT
before
after
Even if my data were somehow messed up, i'd expect at least to see
before
during
after
What am I not understanding here, why isn't getJSON() firing?
You are using
return render_template('index.html', data=data)
You need to return ONLY data when you call the .getJSON function. simple
return data
should work. Because getJSON doesn't allow POST request you'll have to add one more route
#app.route('/')
def index_html():
return render_template('index.html')
#app.route("/getjson")
def json():
data = {"this":"is", "just":"a test"}
return data
and change your getJSON request to
$.getJSON("/getjson", function(data){
console.log("during")
console.log(JSON.stringify(data));
});
Related
I have made a flask app that detects the changes made in a log file like the tail-f command in UNIX, but when I run it and make changes in the log file the output is not displayed on the webpage, I have written the code with reference to this,
Here is my flask app
import time
import os
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/logs')
def logs():
def generate():
with open("log.log") as f:
while True:
# read last line of file
line = f.readline()
# sleep if file hasn't been updated
if not line:
time.sleep(0.1)
continue
yield line
return app.response_class(generate(), mimetype='text/plain')
app.run(debug=True)
Here is the log file, just for the sake of simplicity I have created a dummy log file
like this
1
2
3
4
5
and here is the index.html file
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre id="output"></pre>
<meta charset="utf-8">
<title>Logs</title>
<p>LOGS</p>
<script>
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('logs') }}');
xhr.send();
setInterval(function() {
output.textContent = xhr.responseText;
}, 1000);
</script>
</body>
</html>
Now when I run this Flask App nothing is diplayed on the localhost server, what am I doing wrong here, so that I can get the logs displayed without refreshing the webpage?
In my opinion you should use a reader to read the stream. This means that the end of the transmission is not waited for, but is read in piece by piece.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<pre id="output"></pre>
<script type="text/javascript">
(() => {
fetch('/logs')
.then(response => {
const elem = document.getElementById('output');
const reader = response.body.getReader();
const readStream = ({ done,value }) => {
if (done) {
return;
}
let chunk = String.fromCharCode.apply(null, value);
elem.textContent += chunk + '\n';
return reader.read().then(readStream);
};
reader.read().then(readStream);
});
})();
</script>
</body>
</html>
I am working on a project where I can stream audio live to a HTML file from a server, I am using flask_socketio and Socket io for my client side. I am not sure why it is working, here is my code.
server.py
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app, cors_allowed_origins='*')
with open("bensound-spinningcollins.wav", "rb") as fwav:
data = fwav.read(8)
while data:
data = fwav.read(8)
#socketio.on('message')
def handleMessage(msg):
print('User has connected')
while True:
send(data)
if __name__ == '__main__':
socketio.run(app)
this is my client code
<html>
<head>
<title>Chat Room</title>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Quicksand&display=swap" rel="stylesheet">
<script src="https://cdn.socket.io/3.1.1/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script type="text/javascript">
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function() {
socket.send('connect');
});
socket.on('message', function(msg) {
audioObj = new Audio(msg);
audioObj.play();
});
</script>
</body>
</html>
Not enough rep to comment, so sorry for the reply.
I think the thing you are actually looking for is WebRTC.
Socket.io is great for sending messages back and forth but not so great at streaming something continuously.
If you try to just play a sound on a message, why not access the audio from JS directly?
I am trying to reproduce the simply jQuery example from the Flask docs: https://flask.palletsprojects.com/en/1.1.x/patterns/jquery/. It works fine on my local machine, but when I host it on a web server in cgi-bin, getJSON returns false. How can I correct this? Thank you!
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
#app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run()
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>
Basically I want the code below to put the "search" from the backend to the frontend.
I am having trouble getting my flask app to pass data from the back end to the front end using templates and a simple flask structure.
I am open to suggestions for better ways. Also # Daniel Mesejo has been a great help so far in my learning about Flask and ajax/jquery.
here is my app.py
from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def index():
entries = json.dumps(scrape("video games"))
return render_template('index.html', entries= entries)
#app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
if request.method == "POST":
#data = request.form("blah")
#print("blah")
search = request.get_json()
#new_search = json.dumps(scrape(data))
return jsonify(search)
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
here is my index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask app</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="topnav">
<a class="active" href="#home">Home</a>
About
Contact
<form class = "form" action="" method="POST">
<input id ="textbox" name="textbox" type="text" placeholder="Search..">
<button type="submit">submit</button>
</form>
</div>
<p>you searched: {{search}} </p>
<div id="div1">
<p id="p1"></p>
<p id="p2"></p>
</div>
<script>
var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
e.preventDefault();
var value = $("#textbox").val();
alert(value);
$.ajax({
type: 'POST',
url: "parse_data",
data: JSON.stringify({"text" : value}),
contentType: 'application/json; charset=utf-8',
success: function(data){
alert(JSON.stringify(data));
}
});
});
var jsonz = {{ entries|tojson }};
var s = JSON.parse(jsonz);
var i;
for (i = 0; i < s.length; i++) {
var para = document.createElement("p");
var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
//document.getElementById("user").innerHTML =
//obj;
//"Name: " + obj.product_name + "<br>" +
//"Location: " + obj.product_link;
</script>
</body>
</html>
To achieve want that simply change the function you pass to success like this:
success: function (data) {
$("#search-query").text("you search: " + data["text"]);
}
and change the <p> element to <p id="search-query"> you searched: </p>.
To learn more about Flask and web development in general I suggest the Flask Mega Tutorial, in here.
basically I looked everywhere for answers (google), I can't seem to find the solution. Basically what I'm doing is that I have a python server who scrapes sites and returns them to a page (depending on the url) in json. And the server gets the url's from a site where you enter where you want to search and what do you want to search. What I want to do is add cookies to the whole thing, because you can login to some sites for discount. What I can't figure out is how am i supposed to send my site cookies to my server. I'm using simplified code to test/find out how it works first.
Site URL:
http://localhost/looking/test.html
Server URL:
http://localhost:8082
Server request example:
http://localhost:8082/?search=dell&shop=rlyniceshop
HTML CODE
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<button type="button" class="btn btn-outline-success" data-where="ASWO">Prisijungti</button>
<script>
if (Cookies.get('user') == null) {
var user = Date.now();
Cookies.set('user', user);
console.log(Cookies.get('user'));
}
$('.btn-outline-success').on('click', function(){
var url = 'http://localhost:8082/?search=dell&shop=pls';
$.ajax({
url: url,
method: "POST",
cookie: "TestCookie2=AAA"
});
});
</script>
</body>
PYTHON CODE
from http.server import BaseHTTPRequestHandler, HTTPServer
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
import urllib.request
import json
import os
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
crm_path="PATH TO CHROME DRIVER"
class Object:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
parsed = urlparse(self.path)
wow = urllib.parse.parse_qs(parsed.query)
luk = ''.join(wow['search'])
wer = ''.join(wow['parde'])
print(luk+wer);
message = "COMPLEX JSON"
self.wfile.write(bytes(message, "utf8"))
return
def run():
print('starting server...')
server_address = ('127.0.0.1', 8082)
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
print('running server...')
httpd.serve_forever()
run()
If you think I'm unclear on something, please ask.
Right, so I figured it out on my own. It was easy to do as well tbh. Guess not sleeping well caught up with me. What i did was make a new var, where the cookies would be stored and send it as data. Like so:
var dat = Cookies.get()
$('.btn-outline-success').on('click', function(){
var url = 'http://localhost:8082/?search=dell&parde=pls';
$.ajax({
url: url,
method: "POST",
data: dat
});
});
And then get them from my site with get_POST, like so:
def do_POST(self):
self.send_response(200)
self.send_header('Content-type','text/html; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', 'http://localhost')
self.end_headers()
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
parsed_q = urlparse(self.path)
parsed_b = urlparse(body.decode("utf-8"))
search_info = urllib.parse.parse_qs(parsed_q.query)
user_info = urllib.parse.parse_qs(parsed_b.path)
#print(''.join(wow['search']));
print(search_info);
print(user_info);
message = "Json code"
self.wfile.write(bytes(message, "utf8"))
return
This way i could keep my headers and send some additional data (content_length). I kept my do_GET in python code, just for the sake of if i need it in the future.
My current code looks like this now:
PYTHON:
from http.server import BaseHTTPRequestHandler, HTTPServer
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
import urllib.request
import json
import os
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
crm_path="C:\\Users\\Duma\\Desktop\\site\\BrowersDriver\\chromedriver.exe"
class Object:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.send_header('Content-type','text/html; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', 'http://localhost')
self.end_headers()
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
parsed_q = urlparse(self.path)
parsed_b = urlparse(body.decode("utf-8"))
search_info = urllib.parse.parse_qs(parsed_q.query)
user_info = urllib.parse.parse_qs(parsed_b.path)
#print(''.join(wow['search']));
print(search_info);
print(user_info);
message = "Json code"
self.wfile.write(bytes(message, "utf8"))
return
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
message = "Nothing to see here."
self.wfile.write(bytes(message, "utf8"))
return
def run():
print('starting server...')
server_address = ('127.0.0.1', 8082)
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
print('running server...')
httpd.serve_forever()
run()
HTML:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<button type="button" class="btn btn-outline-success" data-where="ASWO">Prisijungti</button>
<script>
if (Cookies.get('user') == null) {
var user = Date.now();
Cookies.set('user', user);
console.log(Cookies.get('user'));
}
var dat = Cookies.get()
$('.btn-outline-success').on('click', function(){
var url = 'http://localhost:8082/?search=dell&parde=pls';
$.ajax({
url: url,
method: "POST",
data: dat
});
});
</script>
</body>
</html>
I hope this will help someone in the future who is looking for something similar :)