url_for with onclick in flask - python

from flask import Flask,render_template,url_for
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/okay")
def okay():
return render_template("okay.html")
if __name__ == '__main__':
app.run(debug=True)
this is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>index</h1>
<h2 onclick="{{ url_for('okay') }}">click me</h2>
<h2>click me</h2>
</body>
</html>
click me
this is not working
also
form action url_for is not working
change route and send message using socketio but socketio is working
how to solve this issue?

When used on a HTML element, onclick normally results to a call to a script function like this onclick=myFunction().
<body>
<h1>index</h1>
<h2 id="foo" onclick="myFunction();">click me</h2>
<h2>click me</h2>
</body>
You'll need to add some Javascript code for onclick=myFunction(); to work.
function myFunction() {
$.ajax({
url: '/okay',
data: JSON.stringify(data),
method: 'POST',
contentType: 'application/json',
success: function(data) {
$('#foo').replaceWith(data);
}
});
};

Related

Linking html frontend and python backend integration

I wanted to integrate my frontend code with my python backend functionality
This is my frontend code with html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Subtitle AI</title>
...
</head>
<body>
<div class="upload">
<h3>Step 1: upload a .wav file</h3>
<input id="wavFile" type="file" name="myFile" accept=".wav" />
<button id="submit-button">Submit</button>
</div>
<h3>Step 2: Wait for model to generate closed captioning</h3>
<p id="result"></p>
<script>
$("#submit-button").click(function(event) {
let parameter1 = {
return1: $("#wavFile").val(),
};
$.post(
"http://127.0.0.1:5000/predict",
JSON.stringify(parameter1),
function(transcription) {
$("#result").text(transcription.result);
console.log(transcription);
}
);
});
</script>
</body>
</html>
And this is my pytohn backend code functionality + attempted integration. I tried to integrate it with Flask, not sure what went wrong, but when I clicked the button, the return value from my python backend function is not displaying.
...
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/predict', methods=['POST'])
...
# define the prediction function which takes in the file path to a wav file and outputs the predicted words
def predict (model, device, path):
...
# decode the IDs to text
transcription = processor.decode(predicted_ids[0])
return jsonify(transcription)

how can I have a flask file wait for a specific button press in a html coded website? - python

I would like to use flask to check when a button is pressed in an HTML coded website, the website will be up and running and the py app needs to be running too and wait for the button click, then on the button click, it will get the input content and print it. How do I do this?
this is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<input type="hallo">
<button>Hallo</button>
</body>
</html>
I have searched for a while but nothing I tried worked, please help.
some code snippets would be great, thanks.
Use a simple form that is submitted with a post request.
The value from the input field is queried using the name attribute.
The button of type submit submits the form.
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print(request.form.get('hallo'))
return render_template('index.html')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<form method="post">
<input type="text" name="hallo" />
<button type="submit">Hallo</button>
</form>
</body>
</html>

How to change CSS class in Python - flask website

What is the simplest way to change class name form .black to .white in the example below using python and flask framework? For example: after mouse click on div #area ?
CSS file:
#area {position:absolute;width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
HTML file:
<!doctype html>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
<div id="area" class="black"></div>
</body>
</html>
This need JavaScript and it has nothing to do with Flask
Example using querySelector()
<div id="area" class="black" onclick="change();"></div>
<script>
area = document.querySelector('#area');
function change(){
area.classList.replace('black', 'white');
}
</script>
or using special variable this
<div id="area" class="black" onclick="change(this);"></div>
<script>
function change(item){
item.classList.replace('black', 'white');
}
</script>
Eventually you could use addEventListener instead of onclick
<div id="area" class="black"></div>
<script>
function change(){
this.classList.replace('black', 'white');
}
area = document.querySelector('#area');
area.addEventListener('click', change);
</script>
or shorter
<div id="area" class="black"></div>
<script>
area = document.querySelector('#area');
area.addEventListener('click', function(){
this.classList.replace('black', 'white');
});
</script>
or even little shorter
<div id="area" class="black"></div>
<script>
document.querySelector('#area').addEventListener('click', function(){
this.classList.replace('black', 'white');
});
</script>
Minimal working code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area1 {width:100px;height:100px;}
#area2 {width:100px;height:100px;}
#area3 {width:100px;height:100px;}
#area4 {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
</head>
<body>
<div id="area1" class="black" onclick="change1();"></div>
<br>
<div id="area2" class="black" onclick="change2(this);"></div>
<br>
<div id="area3" class="black"></div>
<br>
<div id="area4" class="black"></div>
<script>
area1 = document.querySelector('#area1');
function change1(){
area1.classList.replace('black', 'white');
console.log('change1');
}
function change2(item){
item.classList.replace('black', 'white');
console.log('change2');
}
function change3(){
this.classList.replace('black', 'white');
console.log('change3');
}
area3 = document.querySelector('#area3');
area3.addEventListener('click', change3);
area4 = document.querySelector('#area4');
area4.addEventListener('click', function(){
this.classList.replace('black', 'white');
console.log('change4');
});
</script>
</body>
</html>
Using Python you would have to use <a></a> which would send information to server when you click it. And server would use Python to generate HTML with new class and send it back to browser. But it means to reload all page and it needs time.
Minimal working code:
I put black area in <a></a> which ?color=white and when server gets it then it sends back HTML with white area and with ?color=black, etc.
from flask import Flask, request, render_template_string
app = Flask(__name__)
#app.route('/')
def index():
color = request.args.get('color', 'black')
if color == 'black':
other = 'white'
else:
other = 'black'
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
</head>
<body>
<div id="area" class="{{ color }}"></div>
</body>
</html>''', color=color, other=other)
if __name__ == '__main__':
app.run()
It is not popular but you can load JavaScript module Brython to run some Python code in web browser. But you can uses only modules converted to JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.9.1/brython.min.js"></script>
</head>
<body onload="brython()">
<div id="area" class="black"></div>
<script type="text/python">
from browser import document
def change(ev):
if document['area'].attrs['class'] == 'black':
document['area'].attrs['class'] = 'white'
else:
document['area'].attrs['class'] = 'black'
document["area"].bind("click", change)
</script>
</body>
</html>
There is also transcrypt which can convert some Python code to JavaScript code and run in web browser.
Similar module RapydScript
Thanks, but it must be Python. I have found solution for printing a list, for example:
If I create a list called 'content'=['white','black'] the code below will print: white black and it works fine.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
{% for x in content %}
{{x}}
{% endfor %}
</body>
</html>
So according to my question the code below should also work:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
{% if x==1 %}
<div id="area" class="white"></div>
{% else %}
<div id="area" class="black"></div>
{% endif %}
</body>
</html>
But it doesn't, any ideas?

404 error running python script from html button | Google App Engine website hosted

I have an html page, custom.html, and a python script, test.py (both screenshotted below). The html page only has a button that should trigger the python script to print a line (in my next python script I'd like it to do more but this is my starting point).
Under Chrome's developer tools, once I click the button, I receive a GET 404 error, initiated by Jquery. Any advice on successfully activating the python script from my html button is greatly appreciated.
My test.py script is simply
print("Successful line print")
Here is my custom.html document
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<pre>
</pre>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Trigger Python
<script>
function goPython() {
$.ajax({
url: "../folder/test.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
EDIT: I am adding the code to my main.py script required for Google App Engine to handle URL calls and importing Flask.
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template('index.html')
#app.route("/learn.html")
def learn():
return render_template('learn.html')
#app.route("/custom.html")
def custom():
return render_template('custom.html')
if __name__ == "__main__":
app.run()
EDIT 2, after attempting #Dustin Ingram's answer:
Here is the new code to my custom.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Click Here
<script>
function goPython() {
$.ajax({
url: "/trigger-python",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
And I made a simple test.py just to test the ability for the html button click to activate the python script
from flask import Flask
app = Flask(__name__)
#app.route("/trigger-python")
def print_something():
print("Successful line print")
return 'OK'
print_something()
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
After fixing the URL called in AJAX, I'm still getting the same 404 error when clicking the button. Below is an updated Chrome Developer Tool screenshot.
You can't call a Python script via an AJAX request like that. You'll need to call a URL that corresponds to an endpoint of a Python web application.
So, for example, on the frontend:
$.ajax({
url: "/do-something",
context: document.body
})
and then on the backend there is a corresponding route:
#app.route("/do-something")
def do_something():
print("Successful line print")
return 'OK'
See https://cloud.google.com/appengine/docs/standard/python3/quickstart for details on getting started with Python web applications on App Engine.
EDIT: Here's exactly what I've tested and confirmed works:
app.yaml:
runtime: python37
requirements.txt:
Flask==1.1.2
main.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/custom.html')
def custom():
return render_template('custom.html')
#app.route("/trigger-python")
def print_something():
print("Successful line print")
return 'OK'
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
templates/custom.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Click Here
<script>
function goPython() {
$.ajax({
url: "/trigger-python",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
You can see it working here: https://stackoverflow-61195723.uc.r.appspot.com/custom.html

AJAX Request on PhoneGap Server

I'm trying to get AJAX to work on my PhoneGap app. When using the PhoneGap Desktop server, the AJAX request reaches the PythonAnywhere server, as evidenced by the Access Log.
However, when converting it to an APK, the server does not receive a request (not seen in the access log).
HTML: https://pastebin.com/xG5MCf75
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Blank App</title>
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css"/>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
function testAjax(){
alert('button pressed')
$.ajax({
type: "POST",
headers:{'Access-Control-Allow-Origin':'*'},
url: "http://18choym.pythonanywhere.com/testAJAX",
data: {
someData: 'hi'
},
success: function(results){
alert('f1')
// console.log(results["data"])
// alert(results["data"])
alert('f2')
// acessing post data as 'result' returns an obj error.
},
error: function(error){
alert('Error Message: '+error)
}
})
}
</script>
<button onclick='testAjax();'>V3</button>
</body>
</html>
Python: https://pastebin.com/9G6Wdqqi

Categories

Resources