How to output $.get() method JQuery with Flask - javascript

I could not output the data created in Flask to JQuery in a Html page.
I am testing $.get() method in JQuery with Flask. The task is to return a String to a Html page and display it as paragraph. But the result cannot be displayed. Can someone shed a light on this issue. Thanks!
Here is the code in Flask
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/', methods=["GET"])
#app.route('/hello', methods=["GET"])
def hello():
return jsonify('<h1>Hello Flask !!!</h1>')
Here is the html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Events </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function()
{
$("#btnGet").click(function()
{
//$.get('https://httpbin.org/get',
$.get('http://localhost:5000/hello',
function(data)
{
$("#getInfo").text(data)
});
});
});
</script>
</head>
<body>
<button id="btnGet">Click to Get Info </button>
<p id="getInfo"></p>
</body>
</html>

As new to web programming, after hours trial and error, finally found out that I am not placing the html under static folder and run it in Eclipse Environment. After open it up in http://localhost:5000/static/test.html then it works as expected.

Related

Python flask script not executing as expected

I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.
I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.
python code:
from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve
app = Flask(__name__)
#rendering the HTML page which has the button
#app.route('/json')
def json():
return render_template('json.html')
#background process happening without any refreshing
#app.route('/background_process_test')
def background_process_test():
print ("Hello")
return ("nothing")
if __name__ == "__main__":
app.debug = True
serve(app, host='0.0.0.0', port=8080) #WAITRESS!
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
<script src="{{url_for('static', filename='jquery-3.6.0.min.js')}}"></script>
<script type=text/javascript>
(function() {
('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test', function(data) {
//do nothing
})
return false;
})
})
</script>
</head>
<body>
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
</body>
</html>
Update:
Network tab
i somehow deleted the '$' sign. It was giving an error due to spacing in visual studio. Setting the spacing right, solved the issue. Many thanks for pointing me in the right direction.
There is a typo in the following code:
('a#test').on('click', function(e) {
...
})
Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:
$('a#test').on('click', function(e) {
...
})

How can I send captured video stream frames from html to flask server?

I have 3 main code(camera.py, main.py, xx.html) run perfectly in my local server. But I when uploaded them to heroku, application is not working since cv2.VideoCapture isn't triggering webcam on client side.
Main.py:
from flask import Flask, render_template,Response,request,jsonify
from camera import VideoCamera
from flask import redirect,url_for
import os
from PIL import Image
from mains.utils import pipeline_model
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from predictors import RegressionPredictor, CNNPredictor
import numpy as np
UPLOAD_FOLDER ='static/upload'
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
camera.py:
import cv2
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
ds_factor=0.6
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
ret,frame = self.video.read()
frame = cv2.resize(frame,None,fx=ds_factor,fy=ds_factor,interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
face_rects = face_cascade.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in face_rects:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
break
ret,jpeg = cv2.imencode('.jpg',frame)
return jpeg.tobytes()
.html code (only related part)
<img id="bg" src="{{url_for('video_feed')}}" alt="">
As I mentioned above code opens my webcam on my browser and detects my face.
I searched and found some javascript code to reach web cam on the client side. Code is like below;
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<body>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="static/webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
</body>
</html>
This code works perfectly but I can not figured out how can I send data frames from "Webcam.attach('#my_camera') to flask server to process it using OpenCV? I searched a lot but couldn't find solution maybe its because I am newbie on javascript.
Thanks in advance for your support!
SocketIO was the answer to make connection between server and javascript code.
Please check this repo for more information.
Please check this one to get OpenCV integrated version of above code

Can't play audio on Python Flask server, but works fine on local

I have written a Python Flask program, MusicServer.py, that creates a server on my local network and have connected the render_template() to my HTML page.html file. When I run the server, everything loads as intended, but the buttons to play the music no longer work, even though they work as intended when I press the buttons to play the music when I run the standalone page.html file.
I have already tried attempting to play the audio files by running them to play through the actual python server file, I tried an HTML form, I tried Javascript, which also works as intended on the raw HTML execution but not the server, and I have tried using the built in HTML audio tag.
***python MusicServer.py
from flask import Flask, render_template
import os
import socket
app = Flask(__name__)
#app.route("/")
def main():
return render_template('page.html')
if __name__ == "__main__":
print(socket.gethostbyname(socket.gethostname()))
app.run(debug = True, host = "0.0.0.0", port = 80)
os.system("python run MusicServer.py")
***HTML page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
Music Server Test
</title>
</head>
<body bgcolor="pink">
<script type="text/javascript">
var songs = [new Audio('SwedenC418.mp3'),
new Audio('FirefliesOwlCity.mp3')];
var counter = 1;
function playSong(song)
{
if (counter % 2 == 1)
{
song.play();
}
else
{
song.pause();
}
counter = counter + 1;
}
</script>
<h1>
<center>
Welcome to the Music Box!
</center>
</h1>
<button onclick="playSong(songs[0]);" name="SweedenC418">
Sweden- C418 (Caution and Crisis Remix)
</button>
<button onclick="playSong(songs[1]);" name="FirefliesOwlCity">
Fireflies- Owl City
</button>
<audio controls>
<source src="SwedenC418.mp3">
</audio>
</body>
</html>
The expected result is to be able to play audio via button press on an HTML page hosted by Python Flask, but the actual result is only displaying the page with no button functionality.
The two error messages I get in the python console when I try to execute the Fireflies song via HTML button when I try to do it running on the server is
"GET /FirefliesOwlCity.mp3 HTTP/1.1" 404 -
and for the Sweden C418 song the error is
"GET /SwedenC418.mp3 HTTP/1.1" 404 -

Code dynamic dropdown using Python, sqlite3, HTML and JavaScript

I want to fetch userdata from sqlite DB table and list them as a dropdown list in my HTML code. I am new to Python. I tried writing a code, but it failed. list_fetched is my users list that I fetched from db table.
#app.route('/trail', methods=['POST', 'GET'])
def index():
list_tested = db_dropdown()
return render_template("try.html", trail1=list_fetchted)
return "hi"
try.html:
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trail1|tojson }};
function clicked()
{
alert("trail1[0]")
}
</script>
</body>
</html>
No value is getting displayed.
I would recommend looking at the quick start guide for Flask, it may give some advice on your problem and help with your future learning.
(https://flask.palletsprojects.com/en/1.0.x/quickstart/)
I have a solution for your issue (I have removed any sqlite access but sure you can put that in):
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("try.html", trial1=['1', '2'])
Then your try.html file needs to be placed in /templates/try.html in your project directory. By default this is where Flask references templates.
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trial1|tojson }};
function clicked()
{
alert(trail1[0])
}
</script>
</body>
</html>
Enjoy learning python :)

How to load local text information into <div> section

I am trying to draw a diagram by using below codes.
It works well.
As you can see, I should put some text information in the div.
If there is a sample.txt which includes this information in local drive, can I load it into div section dynamically instead of putting it manually?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
Title: Diagram
<!-- Participant FIRST
Participant SECOND
Participant D
Participant F
Participant G //-->
E->F: 2
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 2
SECOND->FIRST: Forward request
FIRST->>C: Send token
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
UPDATE
/test/index.html
/test/js/index.js
/test/js/sample.txt
/test/sample.txt
index.js
// js-sequence-diagrams by bramp <http://bramp.github.io/js-sequence-diagrams/>
$(".diagram").sequenceDiagram({theme: 'simple'});
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
sample.txt
Title: Diagram
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 1
SECOND->FIRST: Forward request
FIRST->>C: Send token
Without inner text
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Add a file-input element to the HTML page:
<input type="file" id="file" onchange="readTxT()"/>
And select sample.txt manually:
function readTxT(){
var reader = new FileReader();
var files=document.getElementById('file').files;
var f = files[0];
reader.onload = function(e) {
var text = reader.result;
$(".diagram").text(text).sequenceDiagram({theme: 'simple'});
}
reader.readAsText(f);
}
The simplest and easy way is to make get request to the server. And for that you have to use jQuery $.get function. Which will make a request for you.
Here is reference to jQuery.get()
USAGE
// make sure the PATH is correct for `sample.txt`
// $.get(your URL to the file, callback function)
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
If the sample.txt is available on the (http) server the site is hosted with (may be localhost), yes.
Assuming your directory structure is like this (/var/www/ is the server's root directory in my example):
/var/www/
index.html (The file without the diagram content)
sample.txt
js/
index.js
Place this in your index.js:
window.onload = function() {
$.get("sample.txt", function(data) {
$(".diagram").text(data).sequenceDiagram({theme: 'simple'});
});
}
If you're not using any HTTP server, you can't load files from the file system directly - that's part of the Javascript sandbox (security concept).
I would then recommend using something like in lx1412's answer, a manual file chooser is the only way how this could work then.
I've tested the script above using Firefox and an HTTP server; and my edit of lx1412's answer using Firefox without an HTTP server.

Categories

Resources