Why is my form trying to submit to the wrong endpoint? - python

I have a python script and a mongoDB instance.
With flask I now want to list all the items of my database on a webpage and use a second webpage to trigger the script to add an other item.
But everytime I click "submit" on the "/add" page, I get a "Method not allowed" and I can see, that it tries to submit it to "/" instead of "/add" ..
script.py
from flask import Flask, render_template, request
import requests, json, sys, getopt, smtplib
from os import system, name
from pathlib import Path
from pymongo import MongoClient
client = MongoClient(port = 27017)
db = client.amazonProducts
allitems = []
allMyItems = []
for document in db.items.find():
allitems.append(document["name"])
def addItem():
for dbWishList in db.wishlist.find():
url = dbWishList["wishlist"]
items = json.loads(requests.get(url).text)
if items:
for item in items:
itemName = str(item["name"])
itemPrice = item["new-price"]
itemUrl = str(item['link'])
if itemPrice:
itemPrice = str(itemPrice[26: ])
itemPrice = str(itemPrice[: itemPrice.find("<")])
itemPriceF = str(itemPrice.replace(".", ""))
itemPriceF = str(itemPriceF.replace("€", ""))
itemPriceF = str(itemPriceF.replace("\xa0", ""))
itemPriceF = str(itemPriceF.replace(",", ".")).replace("\xf6", "")
itemPriceFi = float(itemPriceF)
itemUrl = itemUrl[: itemUrl.find("?coliid")]
itemNameF = itemName.replace('"', '"')
itemNameFi = itemNameF.replace("&amp;", "&")
itemNameFi = itemNameFi.replace("ü", "ue").replace("ö", "oe").replace("ä", "ae").replace(" ", " ").replace("–", "-")
amazonItem = {
'name': itemNameFi,
'url': itemUrl,
'price': itemPriceFi,
'maxPrice': 0
}
db.items.insert_one(amazonItem)
for document in db.items.find():
allMyItems.append(document["name"])
return allMyItems
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("index.html", len = len(allitems), allitems = allitems)
app.run(use_reloader = True, debug = True)
app.config["DEBUG"] = True
#app.route("/add", methods = ["GET", "POST"])
def secPage():
errors = ""
if request.method == "POST":
global testingVar
testingVar = None
try:
testingVar = string(request.form["testingVar"])
except:
errors += "<p>{!r} is not a string.</p>\n".format(request.form["testingVar"])
if testingVar is not None:
addItem()
return render_template("secIndex.html", len = len(allMyItems), allMyItems = allMyItems)
return '''
<html>
<body>
{errors}
<p>What you wanna do?:</p>
<form method="post" action=".">
<p><input name="testingVar" /></p>
<p><input type="submit" value="Do magic" /></p>
</form>
</body>
</html>
'''.format(errors=errors)
index.html
<!DOCTYPE html>
<html>
<head>
<title>For loop in Flask</title>
</head>
<body>
<ul>
<!-- For loop logic of jinja template -->
{%for i in range(0, len)%}
<li>{{allitems[i]}}</li>
{%endfor%}
</ul>
</body>
</html>
secIndex.html
<!DOCTYPE html>
<html>
<head>
<title>For loop in Flask</title>
</head>
<body>
<!-- For loop logic of jinja template -->
<form method="post" action=".">
<p><input name="testingVar" /></p>
<p><input type="submit" value="Do magic" /></p>
</form>
</body>
</html>
The items are built like:
amazonItem = {
'name': itemNameFi,
'url': itemUrl,
'price': itemPriceFi,
'maxPrice': 0
}
Can anyone here follow me and tell me where my mistake might be?

In your form definition you have:
<form method="post" action=".">
The action attribute needs to have the endpoint you want to send the post request to. In your case, you want
<form method="post" action="/add">
If you omit the action attribute, it will submit the post request to the current page, so if you are viewing your form from /add, you can just use
<form method="post">

Related

405: Method Not Allowed. Why am I getting this error in Flask

I tried all posiible ways and read many posts in SO. I haven't got any solution for my "method not allowed" error. Can anyone check and let me know what did I do wrong? I am getting frustrated cause I am new to flask and I cannot proceed further.
This is my template file add_cars.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Datastore and Firebase Auth Example</title>
<script src="https://www.gstatic.com/firebasejs/ui/4.4.0/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.4.0/firebase-ui-auth.css" />
<script src="{{ url_for('static', filename='script.js') }}"></script>
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='navstyle.css') }}">
</head>
<body>
<div class="topnav">
<a class="active" href="{{ url_for('root') }}">Home</a>
EV List
Contact
About
</div>
<h2>Add car details</h2>
<div id="firebase-auth-container"></div>
{% if user_data %}
<p align="right">Email: {{ user_data['email'] }}</p>
<button id="sign-out" hidden="true" style="float: right;">Sign out</button>
<div id="login-info" hidden="true">
<form action="/add_cars" method="post">
Car name:<input type="text" value="" name="name_update"/><br/>
Manufacturer:<input type="text" value="" name="manufacturer_update"/><br/>
Year:<input type="number" value="" name="year_update"/><br/>
Battery size:<input type="number" value="0.0" name="battery_update" step="any"/><br/>
Range:<input type="number" value="" name="range_update"/><br/>
Cost:<input type="number" value="" name="cost_update"/><br/>
Power:<input type="number" value="" name="power_update" step="any"/><br/><br>
<input type="submit" class="button-1" value="Add details" name="submit_button"/>
</form>
{% elif error_message %}
<p>Error Message: {{ error_message }}</p>
{% endif %}
</div>
<br>
<!-- <div>-->
<!-- View all cars-->
<!-- </div>-->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js"></script>
<script src="{{ url_for('static', filename='app-setup.js') }}"></script>
</body>
</html>
This is my main.py
from flask import Flask, render_template, request, redirect, url_for
import google.oauth2.id_token
from google.auth.transport import requests
from google.cloud import datastore
import os, random
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="google_auth_json.json"
firebase_req_adapter=requests.Request()
app = Flask(__name__)
datastore_client = datastore.Client()
def store_time(email):
entity = datastore.Entity(key = datastore_client.key('User', email, 'visit'))
entity.update({'email' : email})
datastore_client.put(entity)
def retrieveCarInfo(claims):
entity_key = datastore_client.key('CarInfo', claims['email'])
entity = datastore_client.get(entity_key)
return entity
def createCarInfo(claims):
entity_key = datastore_client.key('CarInfo', claims['email'])
entity = datastore.Entity(key = entity_key)
entity.update({
'email': claims['email'],
'name': claims['name'],
'cars_list': []
})
datastore_client.put(entity)
def retrieveCars(car_info):
car_ids = car_info['cars_list']
car_keys = []
for i in range(len(car_ids)):
car_keys.append(datastore_client.key('car', car_ids[i]))
cars_list = datastore_client.get_multi(car_keys)
return cars_list
def createCarDetails(claims, new_car_string, new_man_string, new_yr_int, new_bt_float, new_rg_int, new_cost_int, new_pr_int):
id = random.getrandbits(63)
entity_key = datastore_client.key('car', id)
entity = datastore.Entity(key = entity_key)
entity.update({
'name': new_car_string,
'manufacturer': new_man_string,
'year': new_yr_int,
'battery_size': new_bt_float,
'range': new_rg_int,
'cost': new_cost_int,
'power': new_pr_int,
})
datastore_client.put(entity)
return id
def addcarToUser(car_info, id):
car_keys = car_info['cars_list']
car_keys.append(id)
car_info.update({
'cars_list': car_keys
})
datastore_client.put(car_info)
def deleteCars(claims, id):
car_info = retrieveCarInfo(claims)
car_list_keys = car_info['cars_list']
car_key = datastore_client.key('Car', car_list_keys[id])
datastore_client.delete(car_key)
del car_list_keys[id]
car_info.update({
'car_info' : car_list_keys
})
datastore_client.put(car_info)
# All functions below to render data to templates
#app.route("/")
def root():
id_token = request.cookies.get("token")
error_message = None
claims = None
car_info = None
cars = None
if id_token:
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token,
firebase_req_adapter)
store_time(claims['email'])
car_info = retrieveCarInfo(claims)
if car_info == None:
createCarInfo(claims)
car_info = retrieveCarInfo(claims)
cars = retrieveCars(car_info)
except ValueError as exc:
error_message = str(exc)
return render_template('index.html', user_data=claims, error_message=error_message,
car_info=car_info, cars=cars)
# return render_template('index.html', user_data=claims, error_message=error_message)
#app.route("/add_cars", methods=['POST'])
def add_ev():
# add ev's
id_token = request.cookies.get("token")
error_message = None
claims = None
car_info = None
if id_token and request.method=='POST':
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token, firebase_req_adapter)
car_info = retrieveCarInfo(claims)
id = createCarDetails(claims,
request.form['name_update'],
request.form['manufacturer_update'],
request.form['year_update'],
request.form['battery_update'],
request.form['range_update'],
request.form['cost_update'],
request.form['power_update'])
addcarToUser(car_info, id)
except ValueError as exc:
error_message = str(exc)
return redirect(url_for("add_ev"))
# return render_template('add-cars.html', user_data=claims, error_message=error_message, car_info=car_info)
#app.route("/list")
def list_ev():
# listing all ev's
id_token = request.cookies.get("token")
error_message = None
claims = None
car_info = None
if id_token:
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token,
firebase_req_adapter)
car_info = retrieveCarInfo(claims)
if car_info == None:
createCarInfo(claims)
car_info = retrieveCarInfo(claims)
except ValueError as exc:
error_message = str(exc)
return render_template('list_ev.html', user_data=claims, error_message=error_message, car_info=car_info)
#app.route('/delete_cars/<int:id>', methods=['POST'])
def deleteCarFromUser(id):
id_token = request.cookies.get("token")
error_message = None
if id_token:
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token, firebase_req_adapter)
deleteCars(claims, id)
except ValueError as exc:
error_message = str(exc)
return redirect('/')
if __name__=='__main__':
app.run(host='127.0.0.1', port=8082, debug=True)
Update:
When you redirect you will eventually send a GET request to your endpoint, however your endpoint only supports POST.
Therefore you should make a different endpoint then, which supports GET and hosts the template you referenced above. Then the form of the template can send a POST to the add_ev endpoint, and then the add_ev redirects to the new GET endpoint and the loop is closed.
Previous suggestion:
Could you try adding GET as a supported method to the below endpoint?
#app.route("/add_cars", methods=['GET', 'POST'])
def add_ev():
# add ev's
...
You need to add support for GET inside your add_ev and limit redirect to POST only (otherwise you will end with endless loop) i.e. something akin to
#app.route("/add_cars", methods=['GET','POST'])
def add_ev():
...
if request.method == 'POST':
return redirect(url_for("add_ev"))
elif request.method == 'GET':
return render_template('add_cars.html')

Flask go to new page on button click

I have a small flask app with an index page where the user selects a directory from a drop down menu. Once the user makes a selection and clicks "submit" on the webpage I would like to send them to a new page with info specific to that directory.
I'm trying to load the new page by simply calling the function after getting the input from the index page. My issue is that clicking submit on the webpage reloads the same index page.
Flask Code:
app = Flask(__name__)
dirname = os.path.dirname(sys.argv[0])
run_path = ""
#app.route("/", methods = ["GET", "POST"])
def index():
dir_loc = "/Users/kregan1/Documents"
dir_data = list(os.listdir(dir_loc))
if request.method == "POST":
run_dir = request.form.get("run_list")
run_path = dir_loc + "/" + run_dir
run(run_path)
return render_template('index.html', data = dir_data)
#app.route("/run", methods = ["GET", "POST"])
def run(run_path):
if os.path.isdir(run_path) == True:
file_lists = []
for f in os.listdir(run_path):
if f.startswith("pattern"):
file_lists.append(run_path + "/" + f)
projects = []
for fl in file_lists:
with open(fl) as f:
for row in f:
if row.split(",")[0] not in projects:
projects.append(row.split(",")[0])
else:
projects = ["a","b","c"]
return render_template('run.html', run = run_path, proj_data = projects )
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{url_for('static', filename='asp_javascript.js')}}"></script>
</head>
<body>
<h2>Packaging Tool - Index</h2>
<p>Select Run:</p>
<form action="{{ url_for("index") }}" method="post">
<select name="run_list">
{% for d in data %}
<option>{{d}}</option>
{% endfor %}
</select>
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
You can use redirect(...) instead of just calling the function.
from flask import redirect
...
if request.method == "POST":
run_dir = request.form.get("run_list")
run_path = dir_loc + "/" + run_dir
return redirect(url_for('run', run_path=run_path))
#app.route("/run/<run_path>", methods = ["GET", "POST"])
def run(run_path):
if os.path.isdir(run_path) == True:
...

Python Forex Calculator Not Complying

I'm trying to complete a forex money converter in FLASK but my code isn't working.
It allows the user input, then once I hit submit the next page that shows Method Not Allowed
The method is not allowed for the requested URL.
-Update, now it just goes to an action page, whenever I try to pull up the Index2.html it doesn't load. I'm not sure why its not allowing me to proceed.
-I'm trying to save three inputs, add them to a list, then convert them into a dollar amount
-Page Refreshes to action page, this is not what is intended
Index.html file
><!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="/index2.html", method="Post">
<label for="C1" name= "C1"> Converting From:</label><br>
<input type="text" id="C1" name="C1"><br>
<label for="C2">Converting To:</label><br>
<input type="text" id="C2_to" name="C2_to"><br>
<label for="amt">Amount:</label><br>
<input type="text" id="amt" name="amt"><br>
<br>
<input type="submit" value="Submit">
</form>
app.py file
from flask import Flask, render_template,request, redirect, session
from forex_python.converter import CurrencyCodes, CurrencyRates
app = Flask(__name__)
app.config["secret key"]="yeah"
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
responses_key= "responses"
#app.route("/")
def show_form():
return render_template("Index.html" )
#app.route("/index2")
def show_form2():
return render_template("index2.html" )
T= CurrencyRates()
#app.route("/Index2", methods=["POST"])
def save_answer():
line2 = request.data.get("C1", "C2", int("amt"))
responses = session[responses_key]
responses.append(line2)
responses = session[responses]
rate = T.convert(line2[0],line2[1],int(line2[2]))
return rate,render_template("/Index2.html", rate="response")
As index2.htlm is not shared, i created a simple 1 liner index2.html to show the conversion. PFB code:
app.py:
from flask import Flask, render_template, request, redirect, session, url_for
from forex_python.converter import CurrencyCodes, CurrencyRates
app = Flask(__name__)
app.config["secret key"] = "yeah"
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
responses_key = "responses"
#app.route('/', methods = ['GET', 'POST'])
def index():
return render_template('Index.html')
T = CurrencyRates()
#app.route("/conversion", methods = ['GET', 'POST'])
def conversion():
if request.method == 'POST':
C1 = request.form.get('C1', None)
C2_to = request.form.get('C2_to', None)
amt = request.form.get('amt', None)
rate = T.convert(C1, C2_to, int(amt))
print(C1, C2_to, amt, rate)
details = {'C1': C1, 'C2_to': C2_to, 'amt': amt, 'rate': rate}
return render_template("Index2.html", details=details)
if __name__ == '__main__':
app.run(host='xx.xx.xx.xx', debug=True)
app.run(debug=True)
Index.html:
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="{{ url_for('conversion') }}" method="post">
<label for="C1" name= "C1"> Converting From:</label><br>
<input type="text" id="C1" name="C1"><br>
<label for="C2_to" name= "C2_to">Converting To:</label><br>
<input type="text" id="C2_to" name="C2_to"><br>
<label for="amt">Amount:</label><br>
<input type="text" id="amt" name="amt"><br>
<br>
<input type="submit" value="Submit">
</form>
Index2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<p> Conversion of {{ details.amt }} {{ details.C1 }} to {{ details.C2_to }} is: {{ details.rate }}</p>
</body>
</html>
Output:
homepage:
conversion page:

Flask: how to update div after processing form inputs

My Flask app does calculations based on user form inputs. These calculation take about 10 seconds to complete. The output of those calculations need to be displayed in a div on the same page, next to the form (in a chart / table etc).
I have tried two aproaches. The first, using normal just Flask, reloads the whole page, which is far from ideal. The second approach, using Sijax, updates just the div. But in this case, i don't know how to access the form inputs.
I'm confused how to get this working. Would appreciate any directions!
Approach 1: just flask (downside: whole page reloads)
form_test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testpage</title>
</head>
<body>
<form action="{{ url_for('do_the_math') }}" method="post">
A = <input type="number" name="input_A">
B = <input type="number" name="input_B">
<input type="submit" value="Submit">
</form>
<div id="destination_div">A + B = {{ result }}</div>
</body>
</html>
app_normal.py:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def show_home():
return render_template("form_test.html", result='unknown yet')
#app.route("/do_the_math", methods=['POST'])
def do_the_math():
A = request.form.get('input_A')
B = request.form.get('input_B')
sum = float(A) + float(B)
# reloads whole page
return render_template("form_test.html", result=sum)
# what i want: reload just update destination_div with new HTML
# return render_template("#destination_div", "A + B = " + str(sum))
if __name__ == '__main__':
app.run(debug=True)
Approach 2: use Sijax (updates div, but how to access form inputs?)
form_test_sijax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testpage with sijax</title>
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
</head>
<body>
<form method="post">
A = <input type="number" name="input_A">
B = <input type="number" name="input_B">
<button type="button" onclick="Sijax.request('submit_form');">calc</button>
</form>
<div id="destination_div">A + B = unknown</div>
</body>
</html>
app_sijax.py
from flask import Flask, render_template, g
import flask_sijax
import os
app = Flask(__name__)
# init sijax
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
flask_sijax.Sijax(app)
def submit_form_handler(obj_response):
A = 5 # how do get to the values entered in the form?
B = 3
sum = A + B
obj_response.html("#destination_div", "A + B = " + str(sum))
#flask_sijax.route(app, "/")
def show_home():
result = 'unknown'
if g.sijax.is_sijax_request:
g.sijax.register_callback('submit_form', submit_form_handler)
return g.sijax.process_request()
return render_template("form_test_sijax.html")
if __name__ == '__main__':
app.run(debug=True)
You can use ajax with jquery to dynamically update the page with the computed result without having to refresh the page:
In the html file:
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</header>
<body>
<div class='wrapper'>
A = <input type="number" id="input_A">
B = <input type="number" id="input_B">
<button class='get_result'>Calculate</button>
<div class='result'></div>
</div>
</body>
<script>
$(document).ready(function(){
$('.wrapper').on('click', '.get_result', function(){
var val1 = $("#input_A").val();
var val2 = $("#input_B").val();
$.ajax({
url: "/calculate_result",
type: "get",
data: {val1: val1, val2:val2},
success: function(response) {
$(".result").html('<p>'+response.result.toString()+'</p>');
},
});
});
});
</script>
</html>
Then, in the main app file, create the route to calculate the final result:
#app.route('/calculate_result')
def calculate_result():
a = int(flask.request.args.get('val1'))
b = int(flask.request.args.get('val2'))
return flask.jsonify({"result":a+b})

Passing a session variable between Templates in Flask

I'm trying to assign a session variable in one Template and pass it to another, but I keep getting KeyError: 'var' error. I'm not sure what I'm doing wrong here. My views.py looks as follows:
from flask import Flask, request, jsonify, session
from app import app
#app.route('/activity', methods=['GET', 'POST'])
def activity():
user = session['var']
location = {'mspace': 'Central Library'}
return render_template('activity.html',
location = location,
user = user)
#app.route('/', methods=['GET', 'POST'])
#app.route('/index', methods=['GET', 'POST'])
def index():
global checkCheck
print "starting"
if request.method == 'POST':
# print(request.data)
checkCheck = True
location = {'mspace': 'Central Library'}
user = {'nickname': request.args.get('name')}
session['var'] = user
# print user['nickname']
print session['var']
return render_template('index.html',
location = location,
user = user)
return render_template('index.html',
location = "test",
user = 'user')
and here's my activity.html:
<html>
<head>
<title>{{ location['mspace'] }} - Makerspace </title>
</head>
<body>
<h1>Hello, {{ user['nickname'] }} - what activity are you doing today:</h1>
<form action="" method="">
<h3> Choose your Activity</h3>
<select name="activity">
<option value='3dprinting'>3D Printing</option>
<option value='Minecraft'>Minecraft</option>
<option value='Arduino'>Arduino</option>
<option value='Wearables'>Wearables</option>
</select>
</body>
</html>
Here's my index.html:
<html>
<head>
<title>{{ location['mspace'] }} - Makerspace </title>
</head>
<body>
<h1>Hello, {{ user['nickname'] }}!</h1>
</body>
<script>
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send(null);
return xmlHttp.responseText;
}
setInterval(checkFunc(), 1000);
function checkFunc(){
var json = httpGet("/getSignIn");
console.log("yes!");
obj = JSON.parse(json);
console.log(obj.newCheckin);
if(obj.newCheckin){
window.location.replace("http://127.0.0.1:5000/activity");
}
else{
setInterval(checkFunc(), 1000);
}
}
</script>
</html>

Categories

Resources