Receive data from HTML forms in fastapi [duplicate] - python

I am facing the following issue while trying to pass a value from an HTML form <input> element to the form's action attribute and send it to the FastAPI server.
This is how the Jinja2 (HTML) template is loaded:
# Test TEMPLATES
#app.get("/test",response_class=HTMLResponse)
async def read_item(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
My HTML form:
<form action="/disableSubCategory/{{subCatName}}">
<label for="subCatName">SubCategory:</label><br>
<input type="text" id="subCatName" name="subCatName" value=""><br>
<input type="submit" value="Disable">
</form>
My FastAPI endpoint to be called in the form action:
# Disable SubCategory
#app.get("/disableSubCategory/{subCatName}")
async def deactivateSubCategory(subCatName: str):
disableSubCategory(subCatName)
return {"message": "SubCategory [" + subCatName + "] Disabled"}
The error I get:
"GET /disableSubCategory/?subCatName=Barber HTTP/1.1" 404 Not Found
What I am trying to achieve is the following FastAPI call:
/disableSubCategory/{subCatName} ==> "/disableSubCategory/Barber"
Anyone who could help me understand what I am doing wrong?
Thanks.
Leo

Option 1
You can have the category name defined as Form parameter in the backend, and submit a POST request from the frontend using an HTML <form>, as described in Method 1 of this answer.
app.py
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')
#app.post('/disable')
def disable_cat(cat_name: str = Form(...)):
return f'{cat_name} category has been disabled.'
#app.get('/', response_class=HTMLResponse)
def main(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Disable a category</h1>
<form method="post" action="/disable">
<label for="cat_name">Enter a category name to disable:</label><br>
<input type="text" id="cat_name" name="cat_name">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>
Option 2
You can have the category name declared as query parameter in your endpoint, and in the frontend use a similar approach to the one demonstrated in your question to convert the value form the form <input> element into a query parameter, and then add it to the query string of the URL (in the action attribute).
Note that the below uses a GET request in contrast to the above (in this case, you need to use #app.get() in the backend and <form method="get" ... in the frontend, which is the default method anyway). Beware that most browsers cache GET requests (i.e., saved in browser's history), thus making them less secure compared to POST, as the data sent are part of the URL and visible to anyone who has access to the device. Thus, GET method should not be used when sending passwords or other sensitive information.
app.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')
#app.get('/disable')
def disable_cat(cat_name: str):
return f'{cat_name} category has been disabled.'
#app.get('/', response_class=HTMLResponse)
def main(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Disable a category</h1>
<form method="get" id="myForm" action='/disable{{ cat_name }}'>
<label for="cat_name">Enter a category name to disable:</label><br>
<input type="text" id="cat_name" name="cat_name">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>
If you instead would like to use a POST request—which is a little safer than GET, as the parameters are not stored in the browser's history, and which makes more sense when updating content/state on the server, compared to GET that should be used when requesting (not modifying) data—you can define the FastAPI endpoint with #app.post() and replace the above template with the below (similar to Method 2 of this answer), which submits the form using POST method after transforming the form data into query parameters:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function (e) {
var myForm = document.getElementById('myForm');
var qs = new URLSearchParams(new FormData(myForm)).toString();
myForm.action = '/disable?' + qs;
});
});
</script>
</head>
<body>
<h1>Disable a category</h1>
<form method="post" id="myForm">
<label for="cat_name">Enter a category name to disable:</label><br>
<input type="text" id="cat_name" name="cat_name">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>
Option 3
You can still have it defined as path parameter, and use JavaScript in the frontend to modify the action attribute of the <form>, by passing the value of the form <input> element as path parameter to the URL, similar to what has been described earlier.
app.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')
#app.post('/disable/{name}')
def disable_cat(name: str):
return f'{name} category has been disabled.'
#app.get('/', response_class=HTMLResponse)
def main(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function (e) {
var myForm = document.getElementById('myForm');
var catName = document.getElementById('catName').value;
myForm.action = '/disable/' + catName;
});
});
</script>
</head>
<body>
<h1>Disable a category</h1>
<form method="post" id="myForm">
<label for="catName">Enter a category name to disable:</label><br>
<input type="text" id="catName" name="catName">
<input class="submit" type="submit" value="Submit">
</form>
</body>
</html>
Option 4
If you would like to prevent the page from reloading/redirecting when hitting the submit button of the HTML <form> and rather get the results in the same page, you can use Fetch API, a JavaScript interface/library, to make an asynchronous HTTP request, similar to this answer, as well as this answer and this answer. Additionally, one can call the Event.preventDefault() function, as described in this answer, to prevent the default action. The example below is based on the previous option (i.e., Option 3); however, the same approach below (i.e., making an asynchronous HTTP request) can also be used for Options 1 & 2 demonstrated earlier, if you would like to keep the browser from refreshing the page on <form> submission.
app.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')
#app.post('/disable/{name}')
def disable_cat(name: str):
return f'{name} category has been disabled.'
#app.get('/', response_class=HTMLResponse)
def main(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault() // Cancel the default action
var catName = document.getElementById('catName').value;
fetch('/disable/' + catName, {
method: 'POST',
})
.then(resp => resp.text()) // or, resp.json(), etc.
.then(data => {
document.getElementById("response").innerHTML = data;
})
.catch(error => {
console.error(error);
});
});
});
</script>
</head>
<body>
<h1>Disable a category</h1>
<form id="myForm">
<label for="catName">Enter a category name to disable:</label><br>
<input type="text" id="catName" name="catName">
<input class="submit" type="submit" value="Submit">
</form>
<div id="response"></div>
</body>
</html>

Just to provide you a feedback and keep track about the solution I've put in place.
As mentioned by #Chris, I went to the proposed solution 3.
Please find below my new code:
== FastAPI ==
# Test TEMPLATES
#app.get("/test",response_class=HTMLResponse)
async def read_item(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
# Disable SubCategory
#app.post("/disableSubCategory/{subCatName}")
async def deactivateSubCategory(subCatName: str):
disableSubCategory(subCatName)
return {"message": "Sub-Category [" + subCatName + "] Disabled"}
# Enable SubCategory
#app.post("/enableSubCategory/{subCatName}")
async def activateSubCategory(subCatName: str):
enableSubCategory(subCatName)
return {"message": "Sub-Category [" + subCatName + "] Enabled"}
== HTML ==
<html>
<head>
<title>Item Details</title>
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("disableSubCategory").addEventListener("submit", function (e) {
var myForm = document.getElementById('disableSubCategory');
var disableSubCatName = document.getElementById('id_disableSubCategory').value;
myForm.action = '/disableSubCategory/' + disableSubCatName;
});
});
</script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("enableSubCategory").addEventListener("submit", function (e) {
var myForm2 = document.getElementById('enableSubCategory');
var enableSubCatName = document.getElementById('id_enableSubCategory').value;
myForm2.action = '/enableSubCategory/' + enableSubCatName;
});
});
</script>
</head>
<body>
<form id="disableSubCategory" enctype="multipart/form-data" method="post">
<label for="subCatName">SubCategory:</label><br>
<input type="text" id="id_disableSubCategory" value=""><br>
<input type="submit" value="Disable" id="disable">
</form>
<form id="enableSubCategory" enctype="multipart/form-data" method="post">
<label for="subCatName">SubCategory:</label><br>
<input type="text" id="id_enableSubCategory" value=""><br>
<input type="submit" value="Enable" id="enable">
</form>
</body>
</html>

Related

Django returns "internal" sign in form

I try to create my own session middleware and my uauth system using Django. I've got the following code:
class CheckSessionsExistMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
...
response = self.get_response(request)
...
response.status_code = 401
response.reason_phrase = 'Unauthorized'
realm = 'some_app'
response['WWW-Authenticate'] = f'Basic real={realm}'
return response
When i set to respone header 'WWW-Authenticate' the string that contains word 'Basic', Django returns "internal" the sign in form and i do not understand.
Link to example of "internal" sign in form that Django returns: https://psv4.userapi.com/c235131/u2000021998/docs/d23/bc9d828c3755/file.png?extra=0qo4COrPeQh3mwjuRs1WoYsB3GVW8WB-Xn01jjtQz7muPVFWRqKjsm0itRqJFhOqjoYoKQGpAqWbG4xNQlJD3_kcs1u0UNct_76s6b1jv0u9oW76cnH2bGBTWWt_hpSQY-OpgxtRj_h56RPnwMZC73NRHw
Is there a way to disable this behavior?
Example of returning html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="login_form" action="http://127.0.0.1:8000/auth/register/" method="post">
<label for="username_input">
Usesrname
</label>
<input type="text" id="username_input" name=""> <br>
<label for="password_input">
Password
</label>
<input type="text" id="password_input" style="margin-left: 10px"> <br>
<input type="submit" value="Sign in">
</form>
Is it first time? Sign up
</body>
</html>
I expected that Django just return to client the header 'WWW-Authenticate' with value 'Basic realm=some_app' and my html form without "internal" sign in form.

The value I got from the jQuery is NoneType in django

I want to implement a function that updates the graph and displays the number of updates when the button is pressed.
However, when I try to get the parameter in view.py using jQuery, it returns NoneType instead of the intended value. What is the problem?
Also, I don't know if this is related, but when I use console.log() in a jQuery function, there is no output on the console of the browser developer tools. This doesn't seem to have anything to do with the error-only mode or the filter I entered in Console.
The error is
TypeError at /graph/update_graph
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
Thank you.
Here is the code
views.py
from xml.etree.ElementInclude import include
from django.shortcuts import render
from django.http import JsonResponse
from . import graphdata
def index(request):
fig = graphdata.get_scatter_figure()
plot_fig = fig.to_html(fig, include_plotlyjs=False)
return render(request, 'graph/index.html', {'graph':plot_fig})
def update_graph(request):
graph = graphdata.get_scatter_figure()
grahp_html = graph.to_html(graph, include_plotlyjs=False)
cnt = int(request.POST.get('count')) # <-- This is the error point
cnt += 1
data = {
"graph": grahp_html,
"count": cnt,
}
return JsonResponse(data)
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- plotly JS Files -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>
<body>
<div id="update-num">0</div>
<div id="update-text">update</div>
<form id="graph-update-form" action="{% url 'graph:update_graph' %}" method="POST">
{% csrf_token %}
<button type="submit" id="upadate-bt">update</button>
</form>
<div class="graph" id="scatter-graph">{{ graph| safe }}</div>
<!-- jquery script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#update-graph-from").on("submit", function(e){
e.preventDefault();
// These outputs will not be displayed in the console
console.log('hello');
console.log($("#update-num").text());
$.ajax(
{
url: "{% url 'graph:update_graph' %}",
type: "POST",
data: {
count: $("#update-num").text(),
},
dataType: "json",
}
)
.done(function(response){
$("#update-num").remove();
$("#update-num").prepend(response.count);
});
});
</script>
</body>
</html>
urls.py
from django.urls import path
from . import views
app_name = "graph"
urlpatterns = [
path('', views.index, name='index'),
path('update_graph', views.update_graph, name='update_graph'),
]
You have form with id="graph-update-form" and you are submitting the form with id="update-graph-from". Also since you already set url in your ajax you don't need your action="{% url 'graph:update_graph' %}" and method="POST" in your form. Also you can directly set your ajax response vale you don't need to remove the element so you don't have to prepend. Change your index.html as
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- plotly JS Files -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>
<body>
<div id="update-num">0</div>
<div id="update-text">update</div>
<form id="graph-update-form">
{% csrf_token %}
<button type="submit" id="upadate-bt">update</button>
</form>
<div class="graph" id="scatter-graph">{{ graph| safe }}</div>
<!-- jquery script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#graph-update-form").on("submit", function (e) {
e.preventDefault();
// These outputs will not be displayed in the console
console.log('hello');
console.log($("#update-num").text());
$.ajax({
url: "{% url 'update_graph' %}",
type: "POST",
'headers': {
'X-CSRFToken': $('#graph-update-form').find('input[name="csrfmiddlewaretoken"]').val()
},
data: {
count: $("#update-num").text(),
},
dataType: "json",
})
.done(function (response) {
$("#update-num").text(response.count);
});
});

How to get the selected value from html select tag using Flask

I know this question has been asked before but I have been through all the posts and none of the solutions seem to work for me.
Please bear with me. I am new to Flask and html and trying to build my first web app.
It's supposed to work as follows: The user uploads an Excel workbook and the workbook headers are displayed in a dropdown list using the html "select" tag. The user should then select one of the headers. I would then like to pass the selected header into a function.
I am able display the workbook headers in the dropdown list, but when I select a header, nothing happens. Does anyone have any idea what I'm doing wrong?
Please see python code below:
import flask
from flask import Flask
from flask import request
import pandas as pd
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def index():
global headers_list
headers_list=[]
if request.method == "POST":
df=request.files["file"]
if df:
df=pd.read_excel(df)
headers_list=get_headers(df)
selected_header = request.form.get("header")
print(str(selected_header)) #to test the code
else:
print("No file selected")
return (flask.render_template("./index.html", headers_list=headers_list))
def get_headers(dataframe):
headers=list(dataframe.columns)
return headers
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8080, debug=True)
HTML below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content=""
<title><Contra Tool</title>
</head>
<body>
<h1>Contra Tool</h1>
<p>Describe functionality</p>
<br/>
</body>
<form action="" method="post" enctype=multipart/form-data>
<label for ="myfile" > Select a file:</label>
<input type="file" id="myfile" name="file" EnableViewState=True>
<input type="submit" value="Upload">
</form>
<br><br>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div>
<form action="" method="POST">
<SELECT class="dropdown-content" name="header" method="POST" action="/">
<ul>
<option value="{{headers_list[0]}}" selected>{{headers_list[0]}}</option>
{% for h in headers_list[1:]%}
<option value="{{h}}">{{h}}</option>
{% endfor %}
</ul>
</SELECT>
</form>
</div>
</div>
<br/>
<input type="submit">
</html>
Since I am assuming that you do not want to save the excel file on the server, in my opinion there remains a variant in which the file is transferred twice.
If the user selects a file, it is transferred in the background to query the header columns. The select element is filled with the information received.
From now on a column can be selected and the form can be transferred.
In my example there are two routes. One to display and process the form and another which on request returns the header columns in JSON format.
from flask import Flask
from flask import abort, jsonify, render_template, request
import pandas as pd
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'file' in request.files:
file = request.files['file']
df = pd.read_excel(file)
head = request.form.get('head');
print(f'selected "{head}"')
return render_template('index.html')
#app.route('/headers', methods=['POST'])
def headers():
if 'file' in request.files:
file = request.files['file']
df = pd.read_excel(file)
headers = list(df.columns)
return jsonify(headers=headers)
abort(400)
If the user selects a file, it is sent to the second route via AJAX. The select element is emptied and refilled and all necessary further elements are made available after the response from the server has been received.
If the user presses submit, the completed form is sent with the file and the selected column.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<select name="head" id="head" disabled>
<option>Choose Header</option>
</select>
<input type="submit" id="submit" disabled />
</form>
<script type="text/javascript">
(() => {
const fileElem = document.getElementById('file');
fileElem.addEventListener('change', evt => {
const formData = new FormData();
formData.append('file', evt.target.files[0]);
fetch('/headers', { method: 'POST', body: formData })
.then(resp => resp.json())
.then(data => {
// clear select options
const selectElem = document.getElementById('head');
for (let i=selectElem.options.length-1; i >= 0; --i) {
selectElem.remove(i);
}
// populate select options
const headers = data['headers'];
for (const head of headers) {
const optElem = document.createElement('option');
optElem.value = head;
optElem.innerHTML = head;
selectElem.append(optElem);
}
selectElem.disabled = false;
const elem = document.getElementById('submit');
elem.disabled = false;
});
});
})();
</script>
</body>
</html>
Remember, this is a minimal example and may need to be adapted and revised to meet your requirements.

Print a text of textbox in HTML with Flask after pressing a button

This is my first exercise in Flask and I would like to understand what I am doing wrong here.
I want to insert a text in a textbox and then visualize it in HTML
I have already looked many answers on StackOverflow, including this:
Set a python variable in flask with a button and javascript
This is my python code:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def my_form():
return render_template('test.html')
#app.route("/", methods=['GET','POST'])
def func_test():
if request.method == 'POST':
text = request.form['Value1']
return render_template('test.html', value1=text)
if __name__ == "__main__":
app.run(port=5000, debug=True)
and this is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form methods="POST">
<p>Login </p><br>
<p>Value1 <input type = "text" name = "Value1" /></p>
<p><input type = "submit" value = "submit" name = "submit" /></p>
</form>
input is {{value1}}
</body>
</html>
What I would like is that after the text is written in the textbox and the button is pressed, the text is printed after input is
Thanks
well, you can wrap your txt result in an if block that only shows when there is value
{% if value %}
input is {{value1}}
{% else %}
input is:
{% endif %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST">
<p>Login </p><br>
<p>Value1 <input type = "text" name = "Value1" /></p>
<p><input type = "submit" value = "submit" name = "submit" /></p>
</form>
input is {{value1}}
</body>
</html>
You're wanting to accept user input from an HTML form, and return that to the page. As far as I know you're going to need some kind of asynchronous Javascript (aka AJAX) to get this done.
Below is a full example modified from How to display a returned input in Flask using Ajax? for your situation.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
<p>Login </p><br>
<form action='/process' method="POST" autocomplete="off">
<div>
<p>Value1 <input type="text" name="value1" id="value1"></p>
<p><button type="submit">Submit</button></p>
</div>
</form>
<p id="input_is"></p>
</body>
</html>
Asychronous Javascript/AJAX, put this in a file called script.js in your static directory:
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
value1 : $('#value1').val(),
},
type : 'POST',
url : '/process'
})
.done(function(data) {
$('#input_is').text(data['response']).show();
});
event.preventDefault();
});
});
And your Flask route:
from flask import jsonify # add to your existing import
#app.route('/process', methods=['POST'])
def process():
user_input = request.form['value1']
print(user_input) # just for debugging purposes
return jsonify({'response' : user_input})

How to build a get-form post in flask

Ok so I am new to flask, and want to know what objects or tools I would use to do this. I want to create a form, where the user inputs some text, clicks a submit button, then the text that they submitted is bound as a python string, and has a function run on it, and that text is then posted back onto the web page they are viewing with the return value of that function it went through. Here is an example:
html form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action = "/" method="get">
<input type="text" name="mail" size="25">
<input type="submit" value="Submit">
</form>
<textarea cols="50" rows="4" name="result"></textarea>
</body>
</html>
Then here is what I believe should be the url function should look like
#app.route('/', methods=['GET', 'POST'])
def form():
if request.method == 'GET':
input_text = request.data #step to bind form text to python string
new_text = textfunction(input_text) #running the function on the retrieved test.
return (new_text) # no idea if this is write, but returns text after modification.
What would be the best way to set this up? Would it be correct to put a variable as the value for the input html? Need some help on this.
Basically, what you want to do is have a block in your template that is only included if the variable has a value set. See the following example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action = "/" method="get">
<input type="text" name="mail" size="25">
<input type="submit" value="Submit">
</form>
{% if result %}
<textarea cols="50" rows="4" name="result">{{ result }}</textarea>
{% endif %}
</body>
</html>
and then in your python code
#app.route('/', methods=['GET', 'POST'])
def index(result=None):
if request.args.get('mail', None):
result = process_text(request.args['mail'])
return render_template('index.html', result=result)
def process_text(text):
return "FOO" + text

Categories