How to do pagination in flask - python-3.x

**python code:**
from flask import Flask, render_template, request, redirect, url_for, session ,flash
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
app = Flask(__name__)
app.secret_key = 'your secret key'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'details'
mysql = MySQL(app)
#app.route('/home')
def home():
if 'loggedin' in session:
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM ml_process_status")
data = cur.fetchall()
return render_template('home.html', username=session['username'], items=data)
return redirect(url_for('login'))
There are 50 rows in phpmyadmin mysql database. Is there any solution to show only 10 rows in first page and next 10 rows in other pages. I have select * query to show all the rows in the page

To do this you have to pass a parameter to your endpoint (which indicates the page to be displayed), and to select the range of records concerned by using OFFSET AND LIMIT inside your sql statement.
Example:
#app.route('/home')
def home():
if 'loggedin' in session:
page = request.args.get('page', 1)
elem_to_display = 10
offset = (page - 1) * elem_to_display
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM ml_process_status LIMIT %s OFFSET %s", (elem_to_display, offset,))
data = cur.fetchall()
return render_template('home.html', username=session['username'], items=data)
return redirect(url_for('login'))

Related

Why is my POST getting a 405? Python-Flask API

I'm currently writing an API in Flask, and am currently trying to me my POST request to work. Ideally, it would add a band to the DB with a band_ID, name, genre, number of gigs, and a rating. For some reason, running the proper POST request in postman returns a 405. I didn't even know an API *I made * would tell me I don't have access to a POST I'm writing. Do I need to change anything to make it have access?
from flask import Flask, request
from flask_restful import Api, Resource
import sqlite3
app = Flask(__name__)
api = Api(app)
class Band(Resource):
def get(self, band_id):
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("SELECT * FROM bands WHERE band_id=?", (band_id,))
result = c.fetchone()
if result:
return {"message": result}
else:
return {"message": "Band not found"}
def post(self):
data = request.get_json()
if not all(key in data for key in ('band_name', 'band_genre', 'gigs', 'rating')):
return {"message": "Missing data"}
band_name = data['band_name']
band_genre = data['band_genre']
gigs = data['gigs']
rating = data['rating']
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("INSERT INTO bands (band_name,band_genre,gigs,rating) VALUES (?,?,?,?)", (band_name,band_genre,gigs,rating))
conn.commit()
return {"message": "Success"}
api.add_resource(Band, '/bands/<int:band_id>')
if __name__ == "__main__":
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS bands")
c.execute("""CREATE TABLE IF NOT EXISTS bands (
band_id INTEGER PRIMARY KEY,
band_name TEXT,
band_genre TEXT,
gigs INTEGER,
rating INTEGER
)""")
conn.commit()
app.run(debug=True)
I've tried changing the call on postman and fiddling around with my add.resource lines but to no avail. Totally lost on what to do next.

FLASK: The new values entered in the form are not getting inserted to the database even though the execution has been committed

from flask import Flask, jsonify, request, url_for, redirect, session, render_template, g
import sqlite3
app = Flask(__name__)
app.config['DATABASE'] = './data.db'
def connect_db():
path = r"C:\Users\Arjun\Documents\flask_app\data.db"
sql = sqlite3.connect(path)
sql.row_factory = sqlite3.Row
return sql
def get_db():
if not hasattr(g, 'sqlite3'):
g.sqlite_db = connect_db()
return g.sqlite_db
#app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
#app.route('/home', defaults={'name':'Default'})
#app.route('/home/<name>')
def home(name):
session['name'] = name
return render_template('home.html', name=name, display = False, mylist = [1,2,3,4]
#app.route('/theform5', methods=['GET', 'POST'])
def theform5():
if request.method == 'GET':
return render_template('form.html')
else:
name = request.form['name']
location = request.form['location']
db = get_db()
db.execute("insert into users (name, location) values (?, ?)", [name, location])
db.commit()
return redirect(url_for('home', name=name, location=location))
#app.route('/viewresults')
def viewresults():
db = get_db()
cur = db.execute('select id, name, location from users')
results = cur.fetchall()
return 'The ID is {}. Name is {}. The location is {}. '.format(results[1]['id'], results[1]
['name'], results[1]['location'])
Error in:
return "The ID is {}. Name is {}. The location is {}".format(results[1]['id'],results[1]['name'],results[1]['location'])
IndexError: list index out of range
Though the table can be edited directly through the terminal, it can't be edited when the flask web app is run.
Browser: Chrome
SQLite: v3.30.1
Python: v3.8.1
Flask: v1.1.1
you have a syntax error in your return statement in your home function. missing ')' at the end.
In order to run db.execute you would have to set up the cursor first:
db = get_db()
cursor = db.cursor()
cursor.execute("insert into users (name, location) values (?, ?)", [name, location])
also, maybe your syntax is off, try this:
cursor.execute("insert into users values('%s', '%s')" %(name, location))
Are these not the answers you are looking for?

Using same connection with multiple resolvers in graphene

I have a code like this,
# SWAMI KARUPPASWAMI THUNNAI
import jwt
import graphene
from flask import request
from auth.helper import medease_token
from database.get_connection import get_connection
from flask_graphql import GraphQLView
class CredentialInformation(graphene.ObjectType):
"""
graphene object type to get the personal information about the user
"""
country_code = graphene.String()
phone = graphene.String()
verified = graphene.Int()
#medease_token
def resolve_country_code(self, root):
customer_token = request.headers["x-access-token"]
decoded_token = jwt.decode(customer_token, verify=False)
customer_id = decoded_token["customer_id"]
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("select country_code from customer_credential where id=%s limit 1", (customer_id, ))
result = cursor.fetchone()
return result["country_code"]
finally:
cursor.close()
connection.close()
#medease_token
def resolve_phone(self, root):
customer_token = request.headers["x-access-token"]
decoded_token = jwt.decode(customer_token, verify=False)
customer_id = decoded_token["customer_id"]
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("select phone from customer_credential where id=%s limit 1", (customer_id, ))
result = cursor.fetchone()
return result["phone"]
finally:
cursor.close()
connection.close()
#medease_token
def resolve_verified(self, root):
customer_token = request.headers["x-access-token"]
decoded_token = jwt.decode(customer_token, verify=False)
customer_id = decoded_token["customer_id"]
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("select verified from customer_credential where id=%s limit 1", (customer_id,))
result = cursor.fetchone()
return result["verified"]
finally:
cursor.close()
connection.close()
def credential_information_wrapper():
return GraphQLView.as_view("graphql", schema=graphene.Schema(query=CredentialInformation))
which uses flask-graphql and graphene for Python graphql. The code works absolutely fine but I think I am missing something here because I need to open new connections in every resolver, and I need to write same query again so there is a data duplication, so is this the right way of doing or am I missing something?
Any help would be highly appreciated! Thank you in advance.
Opening a new connection on every query (resolver in this case) is okay. You could also set a connection pool to minimize the cost of opening connections.
Just curious, what database adapter or ORM are you using? Would be great if you could refactor the connection and cursor steps into a single function to call on every resolver and only have to pass the SQL query string.

How to use the value obtained in POST method outside the function

Below is my directory structure:
/home
|___ /sub_directory
|__abc.py
|__ xyz.py
Below is my xyz.py code:
from flask import Flask, request, redirect, url_for,send_from_directory, jsonify, render_template
import mysql.connector
from mysql.connector import Error
app = Flask(__name__)
try:
connection = mysql.connector.connect(host='127.0.0.1',database='test',user='root',password='')
if connection.is_connected():
db_Info = connection.get_server_info()
cursor = connection.cursor()
cursor.execute("select id,name from skill_category;")
record = cursor.fetchall()
out = [item for t in record for item in t]
except Error as e:
print("Error while connecting to MySQL",e)
#app.route('/', methods=['GET'])
def dropdown():
val = record
return render_template('Rankcv.html', val = val)
#app.route('/get-subskills', methods=['POST'])
def get_subskills():
skills = request.form['select_skills']
cursor.execute("SELECT skill_items.name FROM skill_items WHERE skill_items.category_id = " + skills + " ;")
record = cursor.fetchall()
out = [item for t in record for item in t]
...........
...........
...........
return jsonify(something)
if __name__ == "__main__":
app.run(debug=True)
Now I have to use the value of variable out and skills in abc.py.
I tried importing xyz directly and tried to retrieve the value using function name (get_subskills), but it didnt work. Can someone please explain how to solve this?
Import the abc function into xyz.

Rendering multiple methods to multiple data table projected in single html under single flask routing

For the url (datatab), how may I render all different queries for different methods to multiple DataTables in single HTML page?
Currently only the first method is rendering data from db to table1 and other methods aren't working.
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
def connectToDB():
import psycopg2
connectionString = psycopg2.connect(host='127.0.0.1', user='null',
password='null', dbname='postgres')
try:
return connectionString
except:
print("data khuje pachchi na ")
#app.route('/')
def index():
return render_template('index.html')
#app.route('/datatab)
def doQuery():
conn = connectToDB()
cur1 = conn.cursor()
cur1.execute(
'select datid,datname,pid,usesysid,usename from pg_stat_activity;')
results1 = cur1.fetchall()
return render_template('datatable.html', doQuery=results1)
#app.route('/datatab')
def doQuery1():
conn = connectToDB()
cur2 = conn.cursor()
cur2.execute(
'select datid,datname,pid,usesysid,usename from pg_stat_activity;')
results2 = cur2.fetchall()
return render_template('datatable.html', doQuery1=results2)
def doQuery2():
conn = connectToDB()
cur3 = conn.cursor()
cur3.execute(
'select relid,indexrelid,schemaname,relname,indexrelname from pg_statio_all_indexes;')
results3 = cur3.fetchall()
return render_template('datatable.html', doQuery2=results3)
def doQuery3():
conn = connectToDB()
cur4 = conn.cursor()
cur4.execute(
'select datid,datname,numbackends,xact_commit,xact_rollback from pg_stat_database;')
results4 = cur4.fetchall()
return render_template('datatable.html', doQuery3=results4)
if __name__ == '__main__':
app.run()
This might help you.
#app.route('/datatab')
def doQuery():
conn = connectToDB()
cur1 = conn.cursor()
cur1.execute('select datid,datname,pid,usesysid,usename from pg_stat_activity;')
results1 = cur1.fetchall()
cur2 = conn.cursor()
cur2.execute('select datid,datname,pid,usesysid,usename from pg_stat_activity;')
results2 = cur2.fetchall()
cur3 = conn.cursor()
cur3.execute('select relid,indexrelid,schemaname,relname,indexrelname from pg_statio_all_indexes;')
results3 =cur3.fetchall()
cur4 = conn.cursor()
cur4.execute('select datid,datname,numbackends,xact_commit,xact_rollback from pg_stat_database;')
results4 = cur4.fetchall()
return render_template('datatable.html', doQuery=results1, doQuery1=results2, doQuery2=results3, doQuery3=results4)

Resources