Python Flask Form not working anymore, any ideas why? - python

The app has worked before, but it has been a while. It requests data from the user that gets sent to a machine learning model. The page should be the same with the results posted at the bottom of html page.
app = Flask(__name__, template_folder='templates')
with open(f'model/model.pkl', 'rb') as file:
model = pickle.load(file)
#app.route('/', methods=['GET', 'POST'])
def main():
if request.method == 'GET':
return(render_template('index.html'))
if request.method == 'POST':
input_list = request.form.to_dict()
input_list = list(input_list.values())
input_list = list(map(int, input_list))
result = Predictor(input_list)
if int(result)==1:
prediction='High'
else:
prediction='Low'
return render_template("index.html",prediction_text = 'Thank you for submitting your details. Your credit risk is : {}'.format(prediction))
def Predictor(input_list):
to_predict = np.array(input_list).reshape(1,15)
result = model.predict(to_predict)
return result[0]
I've tried making two templates of the same html form, where one holds the submit button and the other displays the result.

Related

I am seeing this error in server.py file, " The browser (or proxy) sent a request that this server could not understand."

Here I am attaching my server.py and util.py
I have trained a model, and now wish to print the data on user's demand.
server.py
from flask import Flask, request, jsonify
#from waitress import serve
import util
import json
#%run util.ipynb
app = Flask(__name__)
#app.route('/hi')
def hi():
return util.areas()
#app.route('/locations')
def locations():
response = jsonify({
'locations': util.locations()
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
#app.route('/predict_home_price', methods=['GET', 'POST'])
def predict_home_price():
total_sqft = float(request.form['total_sqft'])
location = request.form['location']
size = int(request.form['size'])
bath = int(request.form['bath'])
area_type = request.form['area_type']
balcony = int(request.form['balcony'])
response = jsonify({
'estimated_price': util.get_estimated_price(area_type, location, size, total_sqft, bath, balcony)
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
if __name__ == '__main__':
print('python flask started')
app.run()
#serve(app, host='0.0.0.0', port=50100, threads=1)
util.py
import json
import joblib
import numpy as np
__locations = None
__area = None
__model = None
def get_estimated_price(area_type, location, size, total_sqft, bath, balcony):
x = np.zeros(6)
x[0] = __area.index(area_type)
x[1] = __locations.index(location)
x[2] = size
x[3] = total_sqft
x[4] = bath
x[5] = balcony
return round(__model.predict([x])[0][0],2)
def locations():
return __locations
def areas():
return __area
def load_saved_artifacts():
print("loading saved artifacts...start")
global __data_columns
global __locations
global __area
with open('./artifacts/locations.json','r') as f:
__locations = json.load(f)['data_locations']
with open('./artifacts/area.json','r') as f:
__area = json.load(f)['data_area']
global __model
__model = joblib.load('./artifacts/Banglore_Real_State_Price')
print(" loading artifacts is done")
if __name__ == '__main__':
load_saved_artifacts()
#print(locations())
#print(areas())
print(get_estimated_price('Super built-up Area','Electronic City Phase II',2,1056,2,1))
print(get_estimated_price('Built-up Area','Uttarahalli',3,1440,2,3))
print(get_estimated_price('Super built-up Area','Lingadheeranahalli',3,1521,3,1))
print(get_estimated_price('Super built-up Area','Kothanur',2,1200,2,1))
Immediate help is really appreciated
I have trained a model, and now wish to print the data on user's demand.
I am seeing this error in server.py file, " The browser (or proxy) sent a request that this server could not understand." I checked everything works fine if I am sending data to browser but not when asking for the data, I tried Postman for sending the data.
http://127.0.0.1:5000/predict_home_price -> shows bad request.
http://127.0.0.1:5000/locations -> shows correct data
http://127.0.0.1:5000/hi -> shows correct data
As you mentioned, when you're sending data to the server it works, and that's because you're using a POST request and the request has form data in it.
But when you're "asking for data", you're probably using a GET request, which has no form data in it, and that's why the server responses with an error.
You can modify your code so you can decide what you should do for each type of request:
#app.route('/predict_home_price', methods=['GET', 'POST'])
def predict_home_price():
if request.method == "POST":
# get form data and do something with it
elif request.method == "GET":
# return some value, without looking for form data

How to GET all the ALL DATA from WTForm?

**How To get All Data in a wtf form with a single command in a dictionary or list without needing to write this much lines of code, specifing every single element in the form and geting data seperately
**
#app.route('/add', methods=['POST', 'GET'])
def add_cafe():
form = CafeForm()
if form.validate_on_submit():
print("True")
cafe_name = form.cafe_name.data
cafe_location = form.cafe_location.data
opening_time = form.opening_time.data
closing_time = form.closing_time.data
coffee_rating = form.coffee_rating.data
wifi_strength_rating = form.wifi_strength_rating.data
power_socket_availability = form.power_socket_availability.data
return render_template('add.html', form=form)
The wtforms documentation says that that's Form.data:
A dict containing the data for each field.
In other words,
#app.route('/add', methods=['POST', 'GET'])
def add_cafe():
form = CafeForm()
if form.validate_on_submit():
data = form.data
print("True", data)
# ...
return render_template('add.html', form=form)

Flask: Bad Request POST 400

I use flask and firebase. I have 2 button in satis.html . When user press button2 , i want to retrieve some data from database and show it. But i get " Bad Request " Error.
Heres my code :
#app.route('/satis', methods=['GET', 'POST'])
def satis():
if (request.method == 'POST'):
sehir=request.form['il']
yas=request.form['yas']
id=request.form['id']
gun=request.form['satisgunu']
cins=request.form['cinsiyet']
tarz=request.form['satistarzi']
db = firebase.database()
db.child("names").push({"sehir": sehir,"yas":yas,"id":id,"gun":gun,"cins":cins,"tarz":tarz})
todo = db.child("names").get()
to = todo.val()
if request.form['submit'] == 'add':
db = firebase.database()
users_by_score = db.child("names").order_by_child("id").equal_to("2").get()
us = users_by_score.val()
return render_template('satis.html', t=to.values(),u=us.values())
return render_template('satis.html', t=to.values())
You have only handled for post method. You need to also handle the GET method situation.
#app.route('/satis', methods=['GET', 'POST'])
def satis():
db = firebase.database()
todo = db.child("names").get()
to = todo.val()
if (request.method == 'POST'):
sehir=request.form['il']
yas=request.form['yas']
id=request.form['id']
gun=request.form['satisgunu']
cins=request.form['cinsiyet']
tarz=request.form['satistarzi']
db.child("names").push({"sehir": sehir,"yas":yas,"id":id,"gun":gun,"cins":cins,"tarz":tarz})
if request.form['submit'] == 'add':
db = firebase.database()
users_by_score = db.child("names").order_by_child("id").equal_to("2").get()
us = users_by_score.val()
return render_template('satis.html', t=to.values(),u=us.values())
return render_template('satis.html', t=to.values())

Web2py - Uploading an image

I have in my controller default.py:
def images():
record = db.images(request.args(0))
form = SQLFORM(db.images, record, deletable=True,
upload=URL('download'), fields=['image'])
if request.vars.image!=None:
# form.vars.image_filename = request.vars.image.filename
form.vars.image_filename = "picture_spark_"+str(auth.user.id)
# form.vars.image_filename = "default"
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
return form
def dashboard():
return dict(img_upload_form=images())
In my view dashboard.html, I use the form like this:
{{=img_upload_form}}
However, the problem is that it doesn't work. I choose an image but after I click Submit, there is no change.
Any help is appreciated!
To solve this problem,
I added a print record line to my default.py controller.
What I observed was that the output was None.
My URL is http://127.0.0.1:8000/Spark/default/home. In essence, home.html does an AJAX call to dashboard.html.
Now, in my controller, I defined it as follows:
def dashboard():
return dict(img_upload_form=images())
What I needed to do was return the same form for home.html
def home():
return dict(img_upload_form=images())
This allowed me to successfully upload images!

Django WSGI error

I'm using Django for a per project. When I use an external API call in my views (function based view), I'm getting bad responses.
Here are my code snippits:
views.py
def stock_name(request):
if request.method == 'POST':
form = StockForm(request.POST)
if form.is_valid():
stock_ticker = form.cleaned_data["stock_ticker"]
return render(request, 'article/stockinfo.html', get_search_query(stock_ticker),context_instance=RequestContext(request))
else:
form = StockForm
return render(request, 'article/index.html', {"form" : form })
.
def get_search_query(stock_ticker):
print stock_ticker
api = articleAPI('e4534187a7915ba69b41c1beab029d0f:8:71762357')
articles = api.search(q = stock_ticker,
fq = {"news_desk" : "technology"},
fl = ["headline", "abstract", "pub_date", "news_desk", "_id"],
sort = "newest",
begin_date = str(20100101),
end_date = str(20150401),
)
print articles
return articles
It seems I'm getting some kind of bad response and it looks like a wsgi error. But If run the get_serach_query as a standalone code, it works. The get_search_query takes a stock ticker and retrieves results with New York Times Article API.

Categories