Submit Flask form without re-rendering the page - python

I'm building a form with flask, below is the simplified version of my flask server
app = Flask(__name__)
#app.route("/", methods = ["POST", "GET"])
def main_page():
if request.method == "POST":
# some cool stuff
return render_template("main.html")
if __name__ == "__main__":
app.debug = True
app.run()
The problem is that it re-renders the page when the user submits the form, jumping to the top of the page. That makes the user experience kinda bad.
How to get the data of the form without re-rendering the entire page?

If you want to submit the form data, but don't want to completely re-render the page, your only option is to use AJAX.
In the following example, the form data is sent using the Fetch API. The processing on the server remains essentially the same because the form data is submitted in the same format.
However, since there is usually a response in JSON format here, I advise outsourcing the endpoint, so that there is a separation between HTML and JSON routes.
from flask import (
Flask,
jsonify,
render_template,
request
)
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods=['POST'])
def upload():
# Same cool stuff here.
print(request.form.get('data'))
return jsonify(message='success')
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<form name="my-form" method="post">
<input type="text" name="data" />
<input type="submit" />
</form>
<script type="text/javascript">
(uri => {
// Register a listener for submit events.
const form = document.querySelector('form[name="my-form"]');
form.addEventListener('submit', evt => {
// Suppress the default behavior of the form.
evt.preventDefault();
// Submit the form data.
fetch(uri, {
method: 'post',
body: new FormData(evt.target)
}).then(resp => resp.json())
.then(data => {
console.log(data);
// Handle response here.
});
// Reset the form.
evt.target.reset();
});
})({{ url_for('upload') | tojson }});
</script>
</body>
</html>

Related

How to send a FastAPI response without redirecting the user to another page?

I am creating an API using FastAPI, which receives form-data from an HTML page, process the data (requiring a few moments) and returns a message saying this task is complete.
This is my backend:
from cgi import test
from fastapi import FastAPI, Form, Request
from starlette.responses import FileResponse
app = FastAPI()
#app.post("/")
async def swinir_dict_creation(request: Request,taskname: str = Form(...),tasknumber: int = Form(...)):
args_to_test = {"taskname":taskname, "tasknumber":tasknumber} # dict creation
print('\n',args_to_test,'\n')
# my_function_does_some_data_treatment.main(args_to_test)
# return 'Treating...'
return 'Super resolution completed! task '+str(args_to_test["tasknumber"])+' of '+args_to_test["taskname"]+' done'
#app.get("/")
async def read_index():
return FileResponse("index.html")
This is my frontend code:
<html>
<head>
<h1><b>Super resolution image treatment</b></h1>
<body>
<form action="http://127.0.0.1:8000/" method="post" enctype="multipart/form-data">
<label for="taskname" style="font-size: 20px">Task name*:</label>
<input type="text" name="taskname" id="taskname" />
<label for="tasknumber" style="font-size: 20px">Task number*:</label>
<input type="number" name="tasknumber" id="tasknumber" />
<b><p style="display:inline"> * Cannot be null</p></b>
<button type="submit" value="Submit">Start</button>
</form>
</body>
</head>
</html>
So the frontend page looks like this:
When the processing is finished in the backend, after the user submitted some data, the return statement from FastAPI backend simply redirects the user to a new page showing only the return message. I was looking for a alternative that would keep the HTML form appearing and display the message returned from the server below this form. For example:
I searched in FastAPI documentation about requests, but I haven't found anything that could avoid modifying my original HTML page.
You would need to use a Javascript interface/library, such as Fetch API, to make an asynchronous HTTP request. Also, you should use Templates to render and return a TemplateResponse, instead of FileResponse, as shown in your code. Related answers can also be found here and here, which show how to handle <form> submission on the submit event, and prevent the default action that causes the page to reload. If you would like to post JSON data instead, have a look at this answer, while for posting both Files and Form/JSON data, have a look at this answer.
Working Example:
app.py
from fastapi import FastAPI, Form, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
#app.post("/submit")
async def submit(request: Request, taskname: str = Form(...), tasknumber: int = Form(...)):
return f'Super resolution completed! task {tasknumber} of {taskname} done'
#app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
templates/index.html
<!DOCTYPE html>
<html>
<body>
<h1>Super resolution image treatment</h1>
<form method="post" id="myForm">
<label for="taskname" style="font-size: 20px">Task name*:</label><br>
<input type="text" name="taskname" id="taskname"><br>
<label for="tasknumber" style="font-size: 20px">Task number*:</label><br>
<input type="number" name="tasknumber" id="tasknumber">
<p style="display:inline"><b>* Cannot be null</b></p><br><br>
<input type="button" value="Start" onclick="submitForm()">
</form>
<div id="responseArea"></div>
<script>
function submitForm() {
var formElement = document.getElementById('myForm');
var data = new FormData(formElement);
fetch('/submit', {
method: 'POST',
body: data,
})
.then(resp => resp.text()) // or, resp.json(), etc.
.then(data => {
document.getElementById("responseArea").innerHTML = data;
})
.catch(error => {
console.error(error);
});
}
</script>
</body>
</html>

String POST Request to Flask

I'm trying to implement a simple dashboard with Flask that will:
Accept a user text input, with a "submit" button. POST this user input to flask.
Flask accepts this input, does some stuff to it, then makes a GET request to another API.
This GET request returns data and shows it somehow (can just be console.log for now)
As an example, with the star wars API:
User inputs name of a Star Wars character (assume no spelling errors)
Flask reads this input name, and maps it to an ID number, because the Star Wars API accepts id numbers. Form a GET request to the Star Wars API, to get full character information.
For now, we can just console.log character information (e.g. "height", "mass", etc.)
What I have now:
app.py
from flask import Flask, jsonify, request, render_template
import random
import json
app = Flask(__name__)
#app.route("/")
def index():
return render_template('index.html')
#app.route("/form_example", methods=["GET", "POST"])
def form_example():
if request.method == "POST":
language = request.form("character_name")
starwars_dictionary = {"Luke Skywalker":"1", "C-3PO":"2", "R2-D2": "3"}
# starwars_dictionary is a dictionary with character_name:character_number key-value pairs.
# GET URL is of the form https://swapi.co/api/people/<character_number>
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>py-to-JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<h3>Sample Inputs</h3>
<ul>
<li>Luke Skywalker</li>
<li>C-3PO</li>
<li>R2-D2</li>
</ul>
<form method="POST">
Enter Name: <input type="text" name="character_name"><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>
In this current form, when I run the app, it returns "Method not allowed; this method is not allowed for the requested URL".
I'm not sure what I'm missing; it's probably just not wired together properly but I'm not sure what the proper syntax is.
Working version after implementing the accepted answer:
app.py
from flask import Flask, jsonify, request, render_template
import requests
import random
import json
app = Flask(__name__)
#app.route("/index", methods=["GET", "POST"])
def index():
#character_height = "" # init a default value of empty string...seems unwieldy
if request.method == "POST":
character_name = request.form.get("character_name")
# Map user input to a numbers
starwars_dictionary = {"Luke Skywalker":"1", "C-3PO":"2", "R2-D2": "3"}
char_id = starwars_dictionary[character_name]
url = "https://swapi.co/api/people/"+char_id
response = requests.get(url)
response_dict = json.loads(response.text)
character_height = response_dict["height"]
return render_template("index.html", character_height=character_height)
return render_template("index.html")
##app.route("/form_example", methods=["GET", "POST"])
#def form_example():
if __name__ == "__main__":
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>py-to-JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<h3>Sample Inputs</h3>
<ul>
<li>Luke Skywalker</li>
<li>C-3PO</li>
<li>R2-D2</li>
</ul>
<form method="POST" action="/index">
Enter Name: <input type="text" name="character_name"><br>
<input type="submit" value="Submit"><br>
</form>
{{ character_height }}
</body>
</html>
Probably the form is posting to the / endpoint, because you didn't declare a form action.
Needs to be more like:
<form method="POST" action="/form_example">
Or if you want to get snazzy and use Jinja's url_for function:
<form method="POST" action="{{ url_for('form_example') }}">
EDIT: That said, you could handle this with a single route function:
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
language = request.form("character_name")
starwars_dictionary = {"Luke Skywalker":"1", "C-3PO":"2", "R2-D2": "3"}
# Logic to query remote API ges here.
else: # Assume method is GET
return render_template("index.html")
Then make the form action {{ url_for('index') }}

How to passing value to new template by click on href function?

i want to click on href and do javascript function to post some value to python and render new template with that data, this is my code.
index.html
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
Click
<script>
var jsvariable = 'hello world'
function myFunction(){
$.ajax({
url: "/getvalue",
type: "post", //send it through get method
data:{'jsvalue': jsvariable},
})
}
</script>
</body>
</html>
server.py
from flask import Flask, render_template, request, url_for
app = Flask(__name__)
#app.route('/', methods=['GET','POST'])
def index():
return render_template('index.html')
#app.route('/getvalue', methods=['GET','POST'])
def getvalue():
data = request.form['jsvalue']
print(data)
return render_template('index2.html', data=data)
if __name__ == "__main__":
app.run(debug=True)
Now the data that pass from ajax function to getvalue() in python that work properly but it not render to new template, so how can i fix that.
Mate you don't even need ajax for this(I even think it's what's making a problem for you, correct me if I'm wrong but ajax makes a background POST request, it's like the template gets rendered to the background, you need a foreground request)
Also bad practice, you put your script before the body, it shouldn't even go in the head but as further down as possible
Why is using onClick() in HTML a bad practice?
server.py
#app.route('/getvalue', methods=['GET','POST'])
def getvalue():
if request.method=='POST':
data = request.form['jsvalue']
return render_template("index2.html", data=data)
index.html
<form action = "/getvalue" method = "POST">
<input type = "hidden" name = "jsvalue"/>
<input type = "submit" value = "submit"/>
</form>
<script>
var jsvariable = 'hello world';
var el=document.getElementsByName("jsvalue");
el[0].value=jsvariable;
</script>
index2.html
{{data}}

Flask Preventing Form Injection

How can python / flask block foreign form injections?
Consider the following mwe:
app.py
from flask import Flask, request, render template
app = Flask(__name__)
#app.route('/', methods=['GET','POST'])
def helloworld():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
print(request.form['info'])
## do something with the info, like write to a database
return 'nothing'
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="{{ url_for('static', filename='js/fire.js') }}"></script>
</head>
<body>
<p>Hello world!</p>
</body>
</html>
static/js/fire.js
$(document).click(function() {
// post data to flask
$.post('/', {'info': 'test'});
return false;
};
My questions are:
Is injection possible from a foreign website? Follow-up: how could this be done? (e.g., perhaps via a form that posts to my website url?)
If injection is possible, what can I do in the app.py script to block the injection?
Edit
Here is a very basic script that can be used to test injections against the above flask application. The accepted answer blocks this script:
<!DOCTYPE html>
<html>
<body>
<h2>Malicious Form Injection</h2>
<form action='http://127.0.0.1:5000/' method='post'>
Input 1:<br>
<input name="info" value="mal1"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
app.py
from flask import Flask, request, render template
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
CSRFProtect(app)
app.config['SECRET_KEY'] = 'somethignrandom'
#app.route('/', methods=['GET','POST'])
def helloworld():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST': # anything post will autocheck csrf
print(request.form['info'])
## do something with the info, like write to a database
return 'nothing'
if __name__ == '__main__':
app.run(debug=True)
There is no need to pass the secret key to the html template, as CSRFProtect will automatically pass the secret key.
templates/index.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta name='csrf-token' content="{{ csrf_token() }}">
<script type='text/javascript' src="{{ url_for('static', filename='js/fire.js') }}"></script>
</head>
<body>
<p>Hello world!</p>
</body>
</html>
script.js
$(document).click(function() {
// post data to flask
$.post('/', {'info': 'test', '_csrf_token':$('meta[name="csrf-token"]').attr('content')});
return false;
};

Output data on same page after form submit

So I created a small flask program which would take a file , do some processing and returns a stream of data using yield.
I am using html form for file upload and submit. The form sends file to a python script and returns the output. The issue is that the output is presented onto a different page because of the form action attribute whereas I need the output on the same page. Probably inside a div tag.
index.html
<script>
if (!!window.EventSource) {
var source = new EventSource('/upload');
source.onmessage = function(e) {
console.log(e)
var byte = e.data;
var res = byte.split(/\s/);
console.log(res[0])
$("#morse").text(res[0].slice(1,));
}
}
</script>
<form action="/upload" method=post enctype=multipart/form-data >
<p><input type="file" name="file" >
<input type="submit" value="Upload" id="search_form_input">
</form>
<div id="morse" class="info">nothing received yet</div> // this is where is need my data
Python code
#app.route('/')
def index():
return render_template('index.html')
#app.route("/upload", methods=['GET', 'POST'])
def streambyte():
if request.method == 'POST':
f = request.files['file']
list_of_items = unAssign(f) # some file processing
def events():
for i in list_of_items:
yield "data: %s\n\n" % (i)
time.sleep(1) # an artificial delay
return Response(events(), content_type='text/event-stream')
This streams the data on http://localhost:5000/upload whereas I need it on http://localhost:5000.
I tried using redirect with Response but it failed saying TypeError: 'generator' object is not callable
You may not need JavaScript to do this...
Since you need the result on the 'index.html' page (i.e http://localhost:5000), you need to create two routes for the same index page.
The first route will load the fresh form (method attribute not set), while the second will reload the process form (method attribute is set to POST). Both routes will point to same index page.
Here below is how your code should look like:-
index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask App - Output data on same page after form submit</title>
</head>
<body>
<form method=post enctype=multipart/form-data >
<p><input type="file" name="file" >
<input type="submit" value="Upload" id="search_form_input">
</form>
<div id="morse" class="info">nothing received yet</div>
<h3>{{ result }}</h3>
<h3>{{ file_path }}</h3>
<!-- this is where is need my data -->
</body>
</html>
Python code
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route("/", methods=['GET', 'POST'])
def streambyte():
# your file processing code is here...
f = request.files['file']
your_script_result = 'This variable holds the final data output'
# your file processing code is here...
return render_template('index.html', file_path = f, result = your_script_result)
if __name__ == '__main__':
app.run(debug=True)
Read more from this link: Send data from a textbox into Flask?

Categories

Resources