Goal:
User inputs a personal token in the frontend which should get passed to a python script in the backend. The python script receives the token, places it correctly in it's code and executes. The scripts output should then be returned to the frontend.
I also want to keep the frontend and backend separated.
I've managed to pass information from the frontend to the backend and then received it back in my Chrome console.
Frontend is running at localhost:5500
Backend is running at localhost:5000
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p>Insert Token: <input id="token">
<button id="send">Send</button>
<script src="app.js"></script>
</body>
</html>
app.js
$("document").ready(function(){
$("#send").click(function(){
var token = $("#token").val();
$.ajax({
url: "http://localhost:5000/token/",
type: "POST",
contentType: "application/json",
data: JSON.stringify({"token": token})
}).done(function(data) {
console.log(data);
});
});
});
views.py
from flask import Flask, request, jsonify
app = Flask(__name__)
#app.route('/token/', methods=['POST'])
def token_input():
response = request.get_json()
print(response)
return jsonify(response)
#app.after_request
def add_headers(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
return response
if __name__ == "__main__":
app.run(debug=True)
So far, my app gives me:
so_far
My guess is:
I have to make a new python script and wrap my script_that_uses_token.py in a function. Then import that function in views.py and somehow use that in the response..?
Related
I'm working with Python Flask application that uses basic html and javascript for the web part.
I'm sending data from UI to the backend using ajax post request.
After processing of data, from the Python flask app I'm returning the response with render_template. But I'm not able to understand how that can be rendered using ajax on the web browser.
The python flask API returns this:
#app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
try:
if request.method == 'POST':
inputMap = request.get_json()
print(inputMap)
###I have my code here###
return render_template('demo.html', location=minio_results_file_location)
except ReferenceError as e:
return "It is a {} Provide proper referaece of file path"
The "demo.html" is a template in the code directory which i want to load on successful execution
And The ajax function is as follows:
$.ajax({
type: "POST",
url: "execution_pipeline",
data: JSON.stringify(data),
contentType : "application/json",
success: function(response) {
window.location.href = response.redirect;
}
});
But on the web page, where we try to load this Ajax response, i'm getting URL not found.
Is there any solution to this?Or am i doing anything wrong?
Import jsonify and url_for from flask:
from flask import jsonify, url_for
And try returning like this to the ajax call:
#app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
try:
if request.method == 'POST':
inputMap = request.get_json()
print(inputMap)
###I have my code here###
return jsonify({'redirect': url_for('demo.html', location=minio_results_file_location)})
except ReferenceError as e:
return "It is a {} Provide proper referaece of file path"
I am following this tutorial to communicate between python and javascript. I am a beginner to this so I dont understand what exactly I am doing wrong.
Following is my code in index.html which sends a POST request to the python server side when the button is clicked:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
{ "make":"Porsche", "model":"911S" },
{ "make":"Mercedes-Benz", "model":"220SE" },
{ "make":"Jaguar","model": "Mark VII" }
];
window.onload = function() {
// setup the button click
document.getElementById("theButton").onclick = function() {
doWork()
};
}
function doWork() {
console.log("posting data")
// ajax the JSON to the server
$.post("receiver", cars, function(){
});
// stop link reloading the page
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<button type="button" id="theButton">Click Me!</button>
And this is my code on the python side:
import sys
from flask import Flask, render_template, request, redirect, Response
import random, json
app = Flask(__name__)
#app.route('/')
def output():
# serve index template
return render_template('index.html', name='Joe')
#app.route('/receiver', methods = ['GET', 'POST'])
def worker():
print("got some data")
# read json + reply
data = request.get_json()
result = ''
for item in data:
# loop over every row
result += str(item['make']) + ''
return result
if __name__ == '__main__':
app.run()
So, when I press the button in the index.html file, the tutorial says that I will be able to see a server response in the web browser. But even though my server is running, this is what I see in the network tab of developer tools for index.html in the Firefox web browser:
I don't understand what I am doing wrong and how I am supposed to see the communication between the client and server. Any help would be appreciated
Your request is not sending JSON, you have to stringify the cars object to send it as JSON.
function doWork() {
console.log("posting data")
// ajax the JSON to the server
$.post("receiver", JSON.stringify(cars), function(){
}, 'application/json');
// stop link reloading the page
event.preventDefault();
}
I also set the content type to application/json as this is required by request.get_json().
For your network tab issue, you have JS selected so you would not see ajax requests only javascript files. You have to have XHR selected or All.
Javascript data send to python flask with ajax and message 400 - Bad request
I use ajax and I send a data from js to flask.
I send a name "john" to url "/name" and I want flask request it. Actually I can request it and print "John".
But there return 400 - Bad Request. Hope help!!!
Here is my code:
HTML + JS:
<html>
<head>
<title>HOME ||</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function send(){
var data={"name":"John"};
alert(data["name"]);
$.ajax({
type: 'POST',
url:"/name",
data:JSON.stringify(data),
contentType: 'application/json; charset=UTF-8',
});
document.location.href="/name";
};
</script>
</head>
<body>
<script>
send()
</script>
</body>
</html>
Python flask:
from flask import Flask, render_template
from flask import request
import json
app = Flask(__name__, template_folder="html")
#app.route('/')
def home():
return render_template("index.html")
#app.route('/name', methods = ["GET", "POST"])
def name():
print(request.get_json(force=True)["name"])
return "ok"
app.run()
Terminal:
PS C:\Python\flask\test2> python app.py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/May/2021 15:31:13] "GET / HTTP/1.1" 200 -
John
127.0.0.1 - - [06/May/2021 15:31:15] "POST /name HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2021 15:31:15] "GET /name HTTP/1.1" 400 -
Your problem is here >> **document.location.href="/name";**
This line of code is calling a get request to /name in Flask.
Inside /name you are trying to obtain **request.get_json(force=True)["name"]**, but this isn't in the get request.
One option would be to delete document.location.href="/name"; so you are not sending a get request
Or you can check if this argument was passed in Flask by writing:
if 'name' in request.get_json(force=True):
print(request.get_json(force=True)["name"])
return "ok"
else:
return "ok"
This should hopefully handle the bad request error as we are checking if the key exists before accessing it.
This question already has answers here:
How to manage a redirect request after a jQuery Ajax call
(34 answers)
Replace HTML page with contents retrieved via AJAX
(7 answers)
Closed 4 years ago.
Let's say I have this setup
Why after clicking "arrToPython" button flask does not redirect me to "query_result.html"? And more importantly, how can I make it to do so?
I tried creating separate route like and using flask's "redirect" method, but it did not work for me either :(
test.py:
from flask import Flask
from flask import request, url_for
from flask import render_template
from flask import redirect, Response
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def savingImage():
if request.method == 'GET':
return render_template('test.html')
if request.method == 'POST':
return render_template('query_result.html')
if __name__ == '__main__':
app.debug = True
app.run()
Where test.html
<!DOCTYPE html> <html> <head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body>
<input id="arrToPython" type=button value="arrToPython" href="result" onclick = "arrToPython()">
<script type="text/javascript">
function arrToPython(){
var arr = ['one', 'two']
$.ajax({
type: 'POST',
url: 'http://localhost:5000/',
data: JSON.stringify(arr),
}).done(function(){
console.log('sent');
})
}
</script> </body> </html>
And query_result.html
<br> Hola amigo!</br>
Twisted.Web and AJAX
Similar thread already exits . I even took code from there , yet i have the same problem , the twisted server works like a charm, but can't figure out why i can't fetch it with ajax. In similar thread he says that alert comes out , but without data. For me even alert doesn't pop up , yet another ajax functions works , so in general with ajax is everything ok , but exactly with fetching something goes wrong.
As also said in similar thread i can fetch it with curl - $ curl --url http://localhost:8082/test -v , and it shows hello world , so servers works fine 100 % .
Any ideas ?
<script type="text/javascript">
// Submit button
$(function(){
$.ajax({type: "POST",
$('a').click(function(){
url: "http://localhost:8082/test",
data: {},
success: function(data) {alert("Success:" + data);}
});
});
});
</script>
<html>
[...]
Load Favorites Movies...
[...]
</html>
server.py
from twisted.web import server, resource, http
class RootResource(resource.Resource):
def __init__(self):
resource.Resource.__init__(self)
self.putChild('test', TestHandler())
class TestHandler(resource.Resource):
isLeaf = True
def __init__(self):
resource.Resource.__init__(self)
def render_GET(self, request):
return self.render_POST(request)
def render_POST(self, request):
return "hello world!"
if __name__ == "__main__":
import sys
from twisted.internet import reactor
reactor.listenTCP(8082, server.Site(RootResource()))
reactor.run()
Big thank you to Peter Le Bek and Darkporter.
Peter Le Bek asnwer marked as correct , and Darkporter vote up =) from me .
Answer : Peter's answer works out of the box , just the thing that confused me a little bit was the line , where you had to specify the static folder. It is easy ... just sepcify any folder there , put there index.html and it will a root directory , when you access it on the web.
Your javascript is mangled, try this:
wwwdir/index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
</head>
<body>
click me
<script type="text/javascript">
$('a').click(function(){
$.ajax({type: "POST",
url: "http://localhost:8082/test",
data: {},
success: function(data) { alert("Success: " + data); }
});
});
</script>
</body>
</html>
You'll probably still meet the cross-domain HTTP request restriction mentioned by darkporter, to solve this serve your webpage using the same Twisted server:
server.py
from twisted.web import server, resource, http, static
class TestHandler(resource.Resource):
isLeaf = True
def __init__(self):
resource.Resource.__init__(self)
def render_GET(self, request):
return self.render_POST(request)
def render_POST(self, request):
return "hello world!"
if __name__ == "__main__":
import sys
from twisted.internet import reactor
root = static.File('/path/to/wwwdir')
testHandler = TestHandler()
root.putChild('test', testHandler)
reactor.listenTCP(8082, server.Site(root))
reactor.run()
Is the page your JavaScript lives on served from the same host and port? If not you'll have a cross domain issue.