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
>
Related
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)
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}]
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.
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
I created an app with flask but I'm having a problem with multi-user access bcs of the global variables. Whenever I run the script (it might take minutes) and someone else is trying to access the page and run a script there too a collision appear and data by both users mix.
I truly understand that I should be using OOP in this case, but I'm not able to replicate the OOP usage for this app (yes, I'm an OOP beginner ). Can someone please give me a hint or a little bit of code about OOP for this case?
Much appreciated.
Python:
from flask import Flask, render_template, url_for, request, redirect, Response
from datetime import datetime
import time
import pandas as pd
import re
import os
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
start_date = request.form["Start_date"]
end_date = request.form["End_date"]
dates = pd.period_range(start=start_date, end=end_date, freq='D')
global s_date
global f_date
s_date = dates[0]
f_date = dates[-1]
print(s_date, f_date)
query = request.form["query"].strip()
splitted = query.split("\r\n")
global fiii
fiii = pd.DataFrame()
for x in splitted:
print(x)
for date in dates:
print(date)
directory = '/home/USER/Parquets/{}/{:02d}/{:02d}/'.format(date.year, date.month, date.day)
for filename in os.listdir(directory):
if filename.endswith(".parquet"):
df = pd.read_parquet(directory)
df.set_index("query", inplace=True)
if request.form.get('lowercase') == "on":
df.index = df.index.str.casefold()
if request.form.get('sensitive') == "on":
fiii = fiii.append(df.filter(regex=re.compile(x), axis=0))
else:
fiii = fiii.append(df.filter(regex=re.compile(x, re.IGNORECASE), axis=0))
fiii = fiii.groupby(['query'])["total"].sum().sort_values(ascending=False)
if request.form.get('csv') == "on":
return redirect("/getCSV")
else:
pass
# return render_template("index.html")
return fiii.to_frame().to_html(table_id="table")
else:
return render_template("index.html")
#app.route("/getCSV")
def getPlotCSV():
return Response(
fiii.to_csv(encoding="UTF-8", sep="\t", header=True),
mimetype="text/csv",
headers={"Content-disposition":
f"attachment; filename={s_date}-{f_date}.csv"})
if __name__ == "__main__":
app.run(debug=True,port=4444)
HTML:
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mate rialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js /materialize.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel ="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<form class="col s6 offset-s3" action="/" method="POST">
<div class="valign-wrapper col s12">
<h3 class="col s6">Query master</h3>
<div class="right-align input-field col s6">
<button class="btn btn-large btn-floating waves- effect waves-light" type="submit" name="action">
<i class="material-icons right">send</i>
</button>
</div>
</div>
<div class="input-field col s12">
<input type="text" id="date-start" class="datepicker " name="Start_date">
<label for="date-start">Start Date</label>
</div>
<div class="input-field col s12">
<input type="text" id="date-end" class="datepicker" name="End_date">
<label for="date-end">End Date</label>
</div>
<label class="input-field col s12">
<input type="checkbox" name="lowercase" />
<span>Lowercase queries</span>
</label>
<label class="input-field col s12">
<input type="checkbox" name="sensitive" />
<span>Case sensitive</span>
</label>
<label class="input-field col s12">
<input type="checkbox" name="csv" />
<span>CSV export (Funkční pouze csv export)</span>
</label>
<div class="input-field col s12">
<textarea id="textarea1" name="query" class="materia lize-textarea"></textarea>
<label for="textarea1">Queries (RegEx supported)</la bel>
</div>
</form>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, {
format: 'm/d/yyyy',
});
});
</script>
</div>
</body>
</html>
Your problem has absolutely nothing to do with OO - it's only the result of using gobal variables.
Your flask server process will serve all incoming requests, one after the other. So what happens in a multi-user scenario is:
1/ user A posts to index. This assigns values to your globals s_date, f_date and fills.
2/ user A is redirected to getCSV
3/ in the meantime, user B posts to index. This rebinds your globals s_date, f_date and fills to new values
4/ user A's browser has followed the redirection, and renders the fill of user B.
The solution is quite simple: do NOT use global state for per-user data persistance - you want either a user session for short-lived session data and/or a RDBMS for long-lived user data.