Python - Flask BadRequestKeyError: 400 Bad Request: KeyError - python

I keep getting the following error:
BadRequestKeyError: 400 Bad Request: KeyError: 'customer_account_number'
Where am I going wrong? I am using Python 2.7 running Flask.
Here is my python script:
import os
from flask import Flask, render_template, request
template_dir = os.path.abspath('c:/users/ned06')
app = Flask(__name__, template_folder=template_dir)
#app.route('/')
def quiz():
return render_template('test.html')
#app.route('/account_number', methods=['POST'])
def quiz_answers():
customer_account_number = request.form["customer_account_number"]
if __name__ == "__main__":
app.run(debug=True)
and here is my HTML:
<form action="/account_number" method="POST">
<p>Input Customer Account Number</p>
<input name="customer_account_number" </input>
<input type="submit" value="Submit" />
</form>

<input name="customer_account_number" </input>
YOu are missing closing bracket here.

Related

How to receive HTTP POST requests in Python?

Task:
User types into a form a char e.g. "hello".
this should be send as an post requests to python, because it is later analyzed via a python script
here is my server side code:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def result():
print(request.form['foo']) # should display 'bar'
return 'Received !' # response to your request.
if __name__ == '__main__':
app.run()
My html code:
<input class="input-text-input" type="text" placeholder="values" name="website">
How can i get the user input from the php form? What would be the best way? The examples in the internet etc. are overloaded. Maybe i have a general mistake.
To make a request from html form to your python flask API, you can do it this way,
HTML FORM
<form action="{{ url_for('addWebsiteUrl') }}" method="post">
<input class="input-text-input" type="text" placeholder="values" name="website">
<input type="submit" value="Submit">
</form>
FLASK API:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def result():
print(request.form['website']) # should display 'website'
return 'Received !' # response to your request.
if __name__ == '__main__':
app.run()

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)

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

Error 400 Flask

I am getting error 400 when i load my website, i have check everything and nothing seems off.
Thanks
Error:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
What the code does:
It takes a input from a user, that is then saved in a file for use of tracking what a user orders from my drinks machine
import flask
from flask import request
#app.route('/Half1File', methods=['POST'])
def Half1File():
print(request.form['projectFilepath'])
Name = request.form['projectFilepath']
print(Name)
file = open("Tab.txt", "a")
file.write('\n'+Name + ", Drink1Half")
return
print (Name)
#app.route("/Half1Tab")
def Half1Tab():
return """<html>
<form action="/Half1File" method="post">
Project file path: <input type="text" name="Name"><br>
<input type="submit" value="Submit">
</form>
</html>"""
You have to fix the name of the value passed to request in your form, and provide a view in the return statement (i made it easy).
import flask
from flask import request
app = flask.Flask(__name__)
#app.route('/Half1File', methods=['POST'])
def Half1File():
print(request.form)
print(request.form['Name'])
Name = request.form['Name']
print(Name)
file = open("Tab.txt", "a")
file.write('\n'+Name + ", Drink1Half")
return """<html><div>OK : {} </div></html>""".format(Name)
#app.route("/Half1Tab")
def Half1Tab():
return """<html>
<form action="/Half1File" method="post">
Project file path: <input type="text" name="Name"><br>
<input type="submit" value="Submit">
</form>
</html>"""

Flask flash yields 404 error

I am trying to use Flask's flash functionality when a user click's a button on a form. The code correctly is identifying the button push as a POST request, yet the webpage yields a 404 error. I have narrowed it down to flash() because without it, there is no 404 error. What is the issue here?
init.py
from flask import Flask, render_template, flash, request
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def meter_input():
print request.method
if request.method == "POST":
print request.form['phone']
flash('test')
return render_template("input.html")
if __name__ == "__main__":
app.run()
input.html
<html>
<form method="post">
<fieldset>
<div class="form-group">
<input id="phone" name="phone" type="text" value="" placeholder="">
</div>
<div class="form-group">
<input type="submit" id="update" value="Update Data"/>
</div>
</fieldset>
</form>
<BR><BR>
</html>
flask.flash apparently uses the flask.session. But the flask.session cannot be used without having defined a secret key for your app. You could have found this out if you started your server in debug mode (which you only should not do in production).
To start your server in debug mode use:
app.run(debug=True)
To fix you actual problem define a secret key right after the creation of the Flask object
app = Flask(__name__)
app.secret_key = "Some secret string here"
I still don't know why you got a 404. You should have gotten a 500 for internal server error

Categories

Resources