Unable to retrieve the values in flask - python

I have used pymongo and retrieved all the values in collection which is stored in mongo atlas and I wanted only lat so I have stored all the lat like this.
a_float = [a['Lat'] for a in results1]
where results1=collection1.find({}) and collection1 = db["Latitude"]
Now in flask I'm trying to compare the input lat with mongo lat. Every time else condition is being executed. My flask code is as follows
#app.route("/")
def hello():
return render_template('home.html')
#app.route("/echo", methods=['POST'])
def echo():
a=request.form['lat']
b=request.form['long']
if a in a_float:
msg = "present"
return render_template('root.html', msg=msg, a=a, b=b)
else:
msg = "absent"
return render_template('root.html', msg=msg, a=a, b=b)
My HTML code home.html
<!DOCTYPE html>
<head>
</head>
<body>
<form method="POST" action="/echo">
Enter the lat<input type="text" name = 'lat' >
Enter the long<input type="text" name = 'long' >
<input type="submit" value="submit">
</form>
</body>
</html>
root.html
<!DOCTYPE html>
<head>
</head>
<form>
</form>
<body>
{{ msg }}
Lat : {{a}}
Long : {{b}}
</body>
</html>

Are you sure your comparison is the same type?
Try converting before comparison if the list element has float values:
a = float(request.form['long'])
Or
a = request.form.get('long', type=float)
See more about this way here

Related

How I get data from a Input to run a function in Django

I'm following a django tutorial and I have troubles getting the data from a input in my HTML.
This is the code from the tutorial:
views.py
def buscar(request):
if request.GET["prd"]:
producto = request.GET["prd"]
articulo = Escucha.objects.filter(user__icontains=producto)
return render(request, "Producto/resultados_busqueda.html", {"articulo": articulo, "query": producto})
else:
mensaje = "Nos has introducido nada"
return HttpResponse(mensaje)
HTML:
<html lang="en">
<head>
<title>Busqueda de producto</title>
</head>
<body>
<form action="/buscar/" method="get">
<input type="text" name="prd">
<input type="submit" value="Buscar">
</form>
</body>
</html>
And this is the code I try to run:
views.py
def suma(request):
if request.get["first"]:
first = request.GET["Primer"]
second = request.GET["Segundo"]
variable = first + second
return render(request, "resultado.html", {"variable": variable})
else:
mensaje = "lo siento"
return HttpResponse(mensaje)
HTML (pruebas.HTML)
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<form action="/pruebas/" method="get">
<input type="text" name="first">
<input type="text" name="second">
<input type="submit" value="suma">
<p>Resultado: {{ variable }}</p>
</form>
</body>
</html>
And the problem I get is:
AttributeError at /pruebas/
'WSGIRequest' object has no attribute 'get'
Y really don't know what's the problem, for me the two codes are similar.
And the problem I get is: AttributeError at /pruebas/ 'WSGIRequest' object has no attribute 'get'
Y really don't know what's the problem, for me the two codes are similar.
No, the codes are not similar, if you look at it correctly, it should be request.GET["first"] not request.get["first"].
And also in Html you have named the inputs as first and second so the view should be:
def suma(request):
if request.GET["first"]:
first = request.GET["first"]
second = request.GET["second"]
variable = first + second
return render(request, "resultado.html", {"variable": variable})
else:
mensaje = "lo siento"
return HttpResponse(mensaje)

response.form.get getting No Values in flask python application

I am new to flask application. I am trying to loop over input of webapp. Based on which i want to show the result on web app. Html template is fine, UDF is also fine only key_from_web is not fetching any value so result is also blank list.
Html:
<!doctype html>
<html>
<head>
<title>superman </title>
</head>
<body> Enter the Registration Number !</body>
<div class="login">
<form action="{{url_for('details')}}">
<input type="text" name="Siret Number" placeholder="siret if you are in France" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large"> Details </button>
</form>
</div>
<br>
{{ prediction_text }}
</html>
Python:
app = Flask(__name__)
#app.route('/')
def home():
return render_template("sample.html")
#app.route('/details',methods=['Get','POST'])
def details():
d = {'col1': [1,1,2], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
df_dict= {str(k): v.to_json(orient= 'records') for k , v in df.groupby('col1')}
# value entered on web app
key_from_web = request.form.get("Siret Number")
result = []
for key_,val_ in df_dict.items():
"""when key_ is entered it should show json output of MATCHED Key_'s val_"""
if key_ == key_from_web:
result.append(val_)
return render_template("sample.html", prediction_text = f"Company details are : {result}")
#call main fun
if __name__ == "__main__":
app.run(debug=True)
Expected Output:
If user enter 1 it should display respective value [{"col1":1,"col2":3},{"col1":1,"col2":4}]

How do we handle empty forms in Flask?

I've written an app that reads data from a csv file and displays the student id and course id and their marks. I am having difficulty in handling situations when no buttons are selected and no text written and submit is pressed or when something is written in text field and no buttons are selected and submit is pressed.
Flask should render error.html in both of the above situations but I am getting a bad request error.
Please see the below code
from flask import render_template
from flask import Flask, request
from matplotlib import pyplot as plt
def read_csv():# Function to read csv
student_dic = {}
courses = []
file = open("./data.csv")
count = 0
a = file.readlines()
for line in a:
r = line.split(",")
if r[1] not in courses:
courses.append(r[1].strip())
r[2] = r[2].rstrip()
if count == 0:
count = count + 1
continue
if (r[0]) in student_dic:
k = {}
k[(r[1].strip())] = int(r[2])
student_dic[(r[0])].update(k)
else:
student_dic[(r[0])] = {(r[1].strip()): int(r[2])}
return ([student_dic, courses])
def plot_hist(marks_list):# Function to plot
plt.hist(marks_list)
plt.savefig("./static/hist.png")
plt.close()
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == "GET":
return render_template("index.html")
elif request.method == "POST":
option = request.form["ID"]
print("here",option)
dic, courses = read_csv()
if option == "student_id":
user_input = (request.form["id_value"])
if user_input == '':
return render_template("error.html")
else:
if user_input in dic:
student_id_dic = dic[user_input]
total_marks = sum(student_id_dic.values())
return render_template("student_details.html", course_id_data=student_id_dic,
student_id_data=user_input,
total_marks_data=total_marks)
else:
return render_template("error.html")
elif option == "course_id":
user_input_course = request.form["id_value"]
if user_input_course == '':
return render_template("error.html")
else:
if user_input_course in courses:
ct = 0
max_marks = -1
total = 0
mark_list = []
h = 0
for student_id in dic:
for key, value in dic[student_id].items():
if key == user_input_course:
mark_list.append(value)
ct = ct + 1
total = total + value
if value > max_marks:
max_marks = value
plot_hist(mark_list)
return render_template("course_details.html", average_marks=(total / ct), maximum_marks=max_marks,
img='./static/hist.png')
else:
return render_template("error.html")
return render_template("error.html")
return render_template("error.html")
if __name__ == "__main__":
app.run(host='0.0.0.0')
app.debug = True
Here is the index html file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Enter Details</title>
</head>
<body>
<div class="main">
<h1>Enter the details</h1>
<form method="POST" action="/" id = "data-form">
<input type="radio" name="ID" value="student_id" />
<label>Student ID</label>
<input type="radio" name="ID" value="course_id" />
<label>Course ID</label>
<input type="text" name="id_value" />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
This is the error html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Something Went Wrong</title>
</head>
<body>
<div class="main">
<h1>Wrong Inputs</h1>
<p> Something went wrong </p>
<br>
Go Back
</div>
</body>
</html>
This would probably be better handled using form validators, rather than adding logic in the route and custom error pages. If you don't want users to submit the form without certain information, just make it impossible to do (using validators). This will also be a better user experience, since they won't have to click "Go Back" on the error page.
You can use built-in validators, such as DataRequired, and you can also write custom validation functions.

Flask: How to route between html templates and display results from sqlite db?

I''m new to Flask and trying to add routing from home.html to results.html and display results in html instead of raw json.
With the below code I'm able to connect to my .db and query it, for example:
To filter entries based on post id : 127.0.0.1:5000/api/v1/jobs/datascience?Business=ACME
api.py:
import flask
from flask import request, jsonify
import sqlite3
import numpy as np
# Debug allows for changes to be seen in real time.
app = flask.Flask(__name__)
app.config["DEBUG"] = True
def dictFactory(cursor, row):
"""
Function that parses the entries of the database and returns them as a list of dictionaries.
#param cursor -- A cursor object using sqlite.
#param row -- The row of the database being parsed.
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
#app.route('/', methods=['GET'])
def homePage():
return '''
<h1>Datascience Jobs Database</h1>
<h3>You have reached: /home/</h3>
<p>To view all entries in the database: '127.0.0.1:5000/api/v1/jobs/datascience/all' </p>
<p>To filter entries based on country : '127.0.0.1:5000/api/v1/jobs/datascience?country=United%20States' </p>
<p>To filter entries based on post id : '127.0.0.1:5000/api/v1/jobs/datascience?id=81953194' </p>
'''
#app.route('/api/v1/jobs/datascience/all', methods=['GET'])
def apiViewAll():
conn = sqlite3.connect('data/datasciencejobs_database.db')
conn.row_factory = dictFactory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM tblJobs;').fetchall()
return jsonify(all_books)
#app.errorhandler(404)
def pageNotFound(e):
return "<h1>Error 404</h1><p>Page not found.</p>", 404
#app.route('/api/v1/jobs/datascience', methods=['GET'])
def apiViewByFilter():
'''
Function that allows users to filter the results in the API based on specified input.
'''
query_parameters = request.args
id = query_parameters.get('BusinessID')
dateTime = query_parameters.get('date')
cleanContent = query_parameters.get('Business')
country = query_parameters.get('country')
query = "SELECT * FROM tblJobs WHERE"
to_filter = []
if id:
query += ' BusinessID=? AND'
to_filter.append(id)
if dateTime:
query += ' date=? AND'
to_filter.append(dateTime)
if cleanContent:
query += ' Business=? AND'
to_filter.append(cleanContent)
if country:
query += ' country=? AND'
to_filter.append(country)
if not (id or dateTime or cleanContent or country):
return pageNotFound(404)
query = query[:-4] + ';'
conn = sqlite3.connect('data/datasciencejobs_database.db')
conn.row_factory = dictFactory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
app.run()
I think the next step would be to add into api.py something like:
from flask import request, jsonify, Flask, render_template
#app.route('/')
def main_searchPage():
return render_template('home.html')
home.html:
<html>
<head>
<title>Main Dashboard</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/home.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Lato:wght#400;700&display=swap" rel="stylesheet">
</head>
<body>
<h2 class="searchText">Search:</h2>
<form class="searchText" id="searchForm" action="{{ url_for('main_searchPage') }}" method="get">
Business Name: <input class="searchText" id="searchInput" type="text" name="Business"><br>
<input class="searchText" id="searchSubmit" type="submit" value="Submit">
</form>
</body>
</html>
The above html page includes one form field to search by 'Business' and after submitting the form with value 'ACME' I’m trying to get result as for 127.0.0.1:5000/api/v1/jobs/datascience?Business=ACME but instead of raw json it should Display on results.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Results Page</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/results.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Lato:wght#400;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="myResults">
<h3>Your Business {{ Business }}</h3>
<h2>BusinessID {{ BusinessID }}</h2>
<h3>{{ date }}</h3>
<h4>Business Located in: : {{ country }}</h4>
</div>
</body>
</html>
Would someone be able to help me with the above or at least give some pointers regarding what should I change in the code? Thanks!
Try this:
replace return jsonify(results) with return render_template('results.html', results=results)
Then in results.html change your div to something like this:
<div id="myResults">
<h3>Your Business {{ results.Business }}</h3>
<h2>BusinessID {{ results.BusinessID }}</h2>
<h3>{{ results.date }}</h3>
<h4>Business Located in: : {{ results.country }}</h4>
</div>
This template part might need some debugging depending in what results looks like but that's how you pass data from flask to the template.

creating a web page with dropdown with html ,python and mysql

i have created a database in mysql , a code in html and in python as given below. It would be really helpful if someone could point out what i am doing wrong.
html code doesnt load.need a dropdown for 'from destination'. but getting {{tvalue}} instead
HTML code below:(kalyani.html)
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>BlueBus</title>
</head>
<body>
<form action="{{ url_for('bluebus') }}" method="POST">
Date of Travel: <input type="date" name=""><br>
From Destination: <select name= 'tvalue'>
{% for tvalue in data%}
<option value="{{ tvalue }}" selected='selected'>{{ tvalue }}</option>
{% endfor %}
</select>
To Destination: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
Python code below:
import pymysql
import flask
import simplejson as JSON
def data(): # Execute query
hostname='127.0.0.1'
username= 'root'
password= '******'
Database= 'mainkar'
myconnection = pymysql.connect(host=hostname, user=username, password=password, database= Database,autocommit=True)
cursor=myconnection.cursor()
sql = 'SELECT distinct(from_city) from route'
# Parse in a variable into the query
cursor.execute(sql)
list_tested = cursor.fetchall() # Get query response and store in variable
list_tested = [i for sub in list_tested for i in sub] # Convert to list from tuple
return (list_tested)
x=data()
htmlFilename = 'kalyani.html'
htmlFile = open(htmlFilename, 'w')
app = flask.Flask(__name__)
#app.route('/bluebus',methods=['POST', 'GET'])
def bluebus():
x=data()
data = x # you can get list from your DB instead
data['selected_tvalue'] = tvalue
return flask.render_template('kalyani.html', **data)
The issue resolved when the function changed in the following way
>
#app.route('/bluebus',methods=['GET','POST'])
def bluebus():
x=data()
for i in range(0,len(x)):
return flask.render_template('kalyani.html',data=x)
i=i+1
>

Categories