How to keep same page in Flask - python

this is a very simple code with Flask. Every time I click submit I go to another page and I lose my input field and my button.
I wonder HOW I can keep the same page and have just a refresh of the page when I have the output. Or if there is any other solution. Thank you
from flask import Flask, render_template_string, request
app = Flask(__name__)
html = """
<div class="form">
<form action="{{url_for('sent')}}" method="POST">
<input title="Title" placeholder="Enter something" type="text" name="line" required> <br>
<button class="go-button" type="submit"> Submit </button>
</form>
</div>
"""
#app.route("/")
def index():
return render_template_string(html)
#app.route("/", methods=['GET', 'POST'])
def sent():
line = None
if request.method == 'POST':
line = request.form['line']
return line
if __name__ == "__main__":
app.run(debug=True)

You can redirect back to the original page after processing the input
Instead of
return line
You can
from flask import redirect, url_for
return redirect(url_for("index"))

Related

Python, flask, methods variable not found. Does the variable no longer exist?

I am trying to send a form to a python server using flask as the framework, however the methods variable keeps giving me an error that no such variable exists. I have tried googling it but haven't found anything online.
from flask import Flask, request
#app.route('/form', methods=['GET', 'POST'])
def form():
# allow for both POST AND GET
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the get request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'
'''
from flask import Flask, request
app = Flask(__name__)
#app.route('/form', methods=['GET', 'POST'])
def form():
# allow for both POST AND GET
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the get request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'
'''
if __name__ == '__main__':
app.run(debug=True)
by adding these two code blocks in the code as shown in the above code, the app is working perfectly fine.
app = Flask(__name__)
if __name__=='__main__':
app.run(debug=True)

Prevent duplicate form submissions while awaiting a response Flask Python

I am running a large request via API and massaging some data before the user sees it. I am looking to prevent the user from clicking the download button while all this information is processed. What would be the best way to accomplish this through a Flask Form?
Here is my HTML:
<form method="POST">
<button type="submit" name="download" value="download" class="button is-primary is-light">Download</button>
{% if error_statement %}
<article class="message is-danger">
<div class="message-body">
{{ error_statement }}
</div>
</article>
{% endif %}
</form>
Here is my Flask Form:
from datetime import date
import pandas as pd
from flask_wtf import FlaskForm
from wtforms import *
from flask import (
Flask,
g,
redirect,
render_template,
request,
session,
url_for,
flash,
Response
)
app = Flask(__name__)
app.secret_key = 'secret'
#app.route('/home', methods=["POST", "GET"])
def home():
class MyForm(FlaskForm):
submit = SubmitField('Download')
if request.method == 'POST':
form = MyForm()
if request.form['download'] == 'download':
#At this point I have code where I call a bunch of APIs and convert data to a CSV file
#This process takes anywhere between 1-3 minutes to complete
if not final_df.empty:
today = date.today()
return Response(final_df.to_csv(index=False, header=True), mimetype="text/csv", headers={"Content-disposition": "attachment; filename=export" + today.strftime("%Y/%m/%d") + ".csv"})
else:
error_statement = 'Something Went Wrong Please Try Again'
return render_template("login.html", error_statement=error_statement)
return render_template('home.html', form=form)
return redirect(url_for('login'))
Can anyone provide guidance on how to prevent the user from clicking the download button while my data is processed?

How to print/Display my search results on the same webpage using Flask and HTML?

I have a dataset of Players and the number of goals they have scored, this dataset is stored in a dataframe. I want to display or print the stats and player details that I have searched for on the search bar, but I am always getting a bad request error
This is the dataset Dataset Screenshot
this is how the Webpage looks like Webpage screenshot
MainProject Python file
import pandas as pd
from pandas import DataFrame
from fuzzywuzzy import process
scorers=pd.read_csv('tests.csv')
def main(searchplayer):
scorers=pd.read_csv('tests.csv')
player=list(scorers['Player'])
goals=list(scorers['Goals'])
team=list(scorers['Team'])
df_data={'player': player,
'goals': goals,
'team': team}
df_main=pd.DataFrame(df_data, columns=['player', 'goals', 'team'])
def getSearchedProducts(searchplayer, choices, limit=30):
res=process.extract(searchplayer, choices, limit=limit)
return res
searchplayer=str(searchplayer)
result=getSearchedProducts(searchplayer, player)
player_result_list = [res[0] for res in result if res[1]>=70]
player_result_df = df_main[df_main['Product'].isin(product_result_list)]
player_result_df.index+=1
list_player_res=[(tabulate(player_result_df, headers='keys', tablefmt='psql'))]
return list_player_res
Flask File
import os
from flask import Flask, flash, request, render_template,
redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from MainProject import main
from flask_cors import CORS
searchplayer=""
app=Flask(__name__)
app.config['CACHE_TYPE']='null'
CORS(app)
#app.route('/', methods=['GET', 'POST'])
def homepage():
searchplayer=request.form['prod']
list_player_res = main(searchplayer)
return render_template('home.html', list_player_res=list_player_res)
if __name__ == "__main__":
app.run()
A code snippet of my Html file
<form class="form-inline" method="POST">
<input class="form-control mr-sm-2" name="prod" type="search" placeholder="Search for Players" aria-label="Search">
<button class="btn btn-light my-sm-0" type="Submit">Search</button>
</form>
This is what I tried:
#app.route('/')
def homepage():
return render_template('home.html')
#app.route('/searchpg', methods=['GET', 'POST'])
def searchpg():
global searchplayer
if request.method == 'POST':
searchplayer = request.form.get['prod']
list_res, list_prod_res = main(searchplayer)
print(list_player_res)
return render_template('home.html', list_player_res=list_player_res)
HTML This is what I did:
<form class="form-inline" method="POST">
<input class="form-control mr-sm-2" name="prod"
type="search" placeholder="Search for Players" aria-label="Search">
<button class="btn btn-light my-sm-0"
type="Submit">Search</button>
</form>
</div>
</nav>
<br>
{% for result in list_player_res %}
{{result}}
{% endfor %}
</br>
How do I search for players in that searchbar and the results get displayed on the same screen?

How to execute Python program within #app.route without 405 error?

I am trying to execute this python back end program once I reach the handle data page. Why are the methods returning a 405 Method Not Allowed error?
In the past, I've tried changing the position of the python to outside of the # decorator and the methods=["POST"] condition
Python
import random
import requests
import time
from datetime import date
import sys
import re
import json
from bs4 import BeautifulSoup
from flask import Flask, render_template, jsonify
app = Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
return render_template('home.html')
#app.route("/handle_data")
def handle_data():
userName = requests.form['username']
listName = requests.form['listname']
full python code is here
randomNumber = randint(0,len(nameList)-1)
films = nameList[randomNumber]
return render_template('home.html', films=films)
if __name__ == '__main__':
app.run(debug=True)
...
HTML
<form action="{{ url_for('handle_data') }}" method="POST">
<form>
<div class="form-row">
<div class="col">
<input type="text" size=15 name=username class="form-control" placeholder="Username">
</div>
<div class="col">
<input type="text" size=15 name=listname class="form-control" placeholder="List Name">
</div>
</div>
<p><input type = "submit" class="buttonclass" value = "Random!" /></p>
</form>
I expect the program to run the requests from the form through the program and return the random list item in form of the variable "films" but I receive a 405 error.
If you need more info, please notify
#app.route("/handle_data") registers the route only for GET requests. If you want POST too, you need to ask for it explicitly:
#app.route("/handle_data", methods=['GET', 'POST'])
def handle_data():
# your code here
or:
#app.route("/handle_data", methods=['GET'])
def handle_get_data():
pass
#app.route("/handle_data", methods=['POST'])
def handle_post_data():
pass
More here: http://flask.pocoo.org/docs/1.0/api/#url-route-registrations

Employing Post Method in Flask

Using the following:
from flask import Flask, render_template
import beautiful_soup_tidal
app = Flask(__name__)
#app.route('/')
def form():
return render_template('form_submit.html')
#app.route('/richmond', methods=['POST'])
def richmond():
someTides = beautiful_soup_tidal.getTides()
return render_template('richmond.html',someTides=someTides)
if __name__ == "__main__":
app.run(debug=True)
And attempting to render the following (richmond.html):
<div id="content" class="form-group">
<form method="post" action="/richmond">
<label style="vertical-align: middle;">channel depth at mean low water
<input type="number" step="0.1" value = "34.5" name="channelDepth"/>FEET</label><br><br>
<label style="vertical-align: middle;">required underkeel clearance
<input type="number" step="0.1" value = "2" name="underkeelClearance"/>FEET</label><br><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
I get the following error: 'The method is not allowed for the requested URL.'
If I delete ', methods=['POST']' in the first section the template renders.
The question: How do I render the template successfully using the post method?
i believe this line should also include GET so that you can render the html form first time round before you actually click submit to post it.
#app.route('/richmond', methods=['POST'])
so it would change to
#app.route('/richmond', methods=['GET', 'POST'])

Categories

Resources