How do i select a random row in admin.view localhost sqlalchemy? - sql

Hi im having hard thinking of how to select a random row from sqlalchemy in a localhost admin database view. I want it to select a random list but the ones with user assigned so it selects a random raffle like `Colour:Ruby up1:dgg2 up2:fh73.below is where the code for the local host database session & view of the database in modelview localhost.
admin = Admin(app, name='raffles', template_mode='bootstrap3')
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Raffle, db.session))
i need help adding code to select a raffle from there
heres the app.py
from flask import Flask, request, render_template, redirect, url_for
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from forms import RaffleForm
from models import db, get_db_uri, User, Raffle
from utils import assign_raffles_to_user, seed_raffles_into_db
from flask import Flask
from flask_mail import Mail
from mail import mail
from flask_mail import Message
app = Flask(__name__)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'osman33454#gmail.com'
app.config['MAIL_PASSWORD'] = 'Password'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = get_db_uri()
app.config['SECRET_KEY'] = 'some-random-secret-key'
mail.init_app(app)
db.app = app
db.init_app(app)
db.create_all()
seed_raffles_into_db()
admin = Admin(app, name='raffles', template_mode='bootstrap3')
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Raffle, db.session))
#app.route('/', methods=['GET', 'POST'])
def home():
form = RaffleForm(request.form)
if request.method == 'POST' and form.validate():
email = form.email.data
# check if user exists
user = User.query.filter_by(email=email).all()
if not user:
user = User(email=email)
db.session.add(user)
else:
user = user[0]
# assign required raffles to user
assign_raffles_to_user(form.raffle_count.data, user)
return redirect(url_for('success'))
return render_template('home.html', form=form)
#app.route('/success', methods=['GET'])
def success():
return render_template('success.html')
if __name__ == '__main__':
app.run(debug=True)
and heres the utils.py
# utility functions go here
import random
import os
from uuid import uuid4
import constants
from models import Raffle, User
from flask_mail import Message
from flask_mail import Mail
from mail import mail
def generate_raffles(count):
for i in xrange(count):
colour = constants.COLORS[i % constants.COLORS_LEN]
uniq = uuid4().hex
uniq_p1, uniq_p2 = uniq[:4], uniq[4:8]
yield (colour, uniq_p1, uniq_p2)
def seed_raffles_into_db(max_raffles=constants.MAX_RAFFLES):
if is_inited():
print 'Raffles have already been seeded...'
return False
from app import db
print 'Seeding raffles...'
for raffle_colour, raffle_up1, raffle_up2 in generate_raffles(max_raffles):
raffle = Raffle(
colour=raffle_colour,
up1=raffle_up1,
up2=raffle_up2,
)
print "Adding", raffle
db.session.add(raffle)
db.session.commit()
mark_as_inited()
return True
def get_unused_raffles(raffle_count):
return (
Raffle.query.filter_by(
user=None
).limit(
constants.RAFFLE_PADDING + raffle_count
)
).all()
def mark_as_inited():
open(constants.INIT_FILE_PATH, 'w').close()
def is_inited():
return os.path.exists(constants.INIT_FILE_PATH)
def assign_raffles_to_user(raffle_count, user):
from app import db
raffles = get_unused_raffles(raffle_count)
for raffle in random.sample(raffles, raffle_count):
print "Assigning {0} to {1}".format(raffle, user)
msg = Message('Raffle assigned', sender = 'osman.soloking009#outlook.com', recipients = [user.email])
msg.body = myRaffle = "Assigning {0} to {1}".format(raffle, user)
mail.send(msg)
raffle.user = user
db.session.commit()
return True
link to see image of my admin view localhost defined tables -where I want the selection to take place

Select a random row with MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 5
Select a random row with IBM DB2
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
Select a random row with Microsoft SQL Server:
SELECT TOP 5 column FROM table
ORDER BY NEWID()
Select a random record with Oracle:
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 5
Select a random row with PostgreSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 5
Select a random row with SQLite:
SELECT column FROM table
ORDER BY
RANDOM() LIMIT 5;

Related

PyQt5 User accessing

We have a university system developed by pyqt5 and python, in the login interface, the instructor can log in by the id and pass, but after login, we have another interface to show the courses of the instructor based on the input id that was from previous interface, the problem that the interface of the courses does not show the courses for the instructor( the id is not accessible to next interface).
I noticed that each interface is not updated when we do action, what is the command to let interfaces' action linked together?
This is the code:
class InstructorLogin(QDialog):
def __init__(self):
super(InstructorLogin, self).__init__()
loadUi("NewInstructorLogin.ui",self)
self.LoginInst.clicked.connect(self.gotoAfterInstLogin)
self.ExitLoginInst.clicked.connect(self.gotoMainExit1)
self.PmuPassInstButton.setEchoMode(QtWidgets.QLineEdit.Password)
#For the password
def gotoAfterInstLogin(self):
global f
global user
user = self.PmuIDInstButton.text()
password = self.PmuPassInstButton.text()
# print(user)
if len(user)==0 or len(password)==0:
self.InvalidPassLab.setText("Please input all fields.")
else:
conn = sqlite3.connect("Cognito.db")
cur = conn.cursor()
query = 'SELECT Password FROM Instructor WHERE Instructor_id =\''+user+"\'"
cur.execute(query)
result_pass = cur.fetchone()[0] #to compare password
if result_pass == password:
self.gotoInstructorLoginAbulBashar()
#####end of noorsol
else:
self.InvalidPassLab.setText("Invalid username or password")
def gotoMainExit1(self):
widget.setCurrentIndex(widget.currentIndex()-1)
#Remove comment later
def gotoInstructorLoginAbulBashar(self):
widget.setCurrentIndex(widget.currentIndex()+15)
# def user_getter(self):
# return user
########################################################################################################################
class ChooseCourseInst(QMainWindow):
global user
def __init__(self):
super(ChooseCourseInst, self).__init__()
#self.afterObj = AfterInstructorLogin()
self.afterInstructorLogin = AfterInstructorLogin()
loadUi("CoursesChosenInt.ui",self)
widget.setCurrentIndex(widget.currentIndex()+4)
self.exitabulbashar.clicked.connect(self.gotoexitabulbashar)
#self.InstServButton.clicked.connect(self.gotoInstServButton)
self.coursesreq.activated.connect(self.gotoInstServButton)
#self.courses(user)
#print(user)
def courses(self):
self.instructorLogin = InstructorLogin()
conn = sqlite3.connect("Cognito.db")
query = 'SELECT DISTINCT Course_name FROM Course WHERE Instructor_id =\''+self.instructorLogin.gotoAfterInstLogin(user)+"\'"
cur = conn.cursor()
cur.execute(query)
final_result = [i[0] for i in cur.fetchall()]
for i in range(len(final_result)):
self.coursesreq.addItem(final_result[i])
def gotoexitabulbashar(self):
widget.setCurrentIndex(widget.currentIndex()-16)
def gotoInstServButton(self):
self.chosencourse = self.coursesreq.currentText()
self.afterInstructorLogin.labeltest.setText(self.chosencourse)
self.afterInstructorLogin.diplayInfo()
#self.afterInstructorLogin.labeltest.show()
widget.setCurrentIndex(widget.currentIndex()-11)
I tried to let the user id as global variable, and create object and call it from the previous class, it shows User not defined, but the i put it inside function and i call that function in another class, it is defined but the courses empty so i expect to know how to refresh interfaces to let the change in first interface reflected in the second

Getting error in a python script when using QuickSight API calls to retrieve the value of user parameter selection

I am working on a python script which will use QS APIs to retrieve the user parameter selections but keep getting the below error:
parameters = response['Dashboard']['Parameters'] KeyError: 'Parameters'
If I try a different code to retrieve the datasets in my QS account, it works but the Parameters code doesn't. I think I am missing some configuration.
#Code to retrieve the parameters from a QS dashboard (which fails):
import boto3
quicksight = boto3.client('quicksight')
response = quicksight.describe_dashboard(
AwsAccountId='99999999999',
DashboardId='zzz-zzzz-zzzz'
)
parameters = response['Dashboard']['Parameters']
for parameter in parameters:
print(parameter['Name'], ':', parameter['Value'])
#Code to display the datasets in the QS account (which works):
import boto3
import json
account_id = '99999999999'
session = boto3.Session(profile_name='default')
qs_client = session.client('quicksight')
response = qs_client.list_data_sets(AwsAccountId = account_id,MaxResults = 100)
results = response['DataSetSummaries']
while "NextToken" in response.keys():
response = qs_client.list_data_sets(AwsAccountId = account_id,MaxResults = 100,NextToken=response["NextToken"])
results.extend(response["DataSetSummaries"])
for i in results:
x = i['DataSetId']
try:
response = qs_client.describe_data_set(AwsAccountId=account_id,DataSetId=x)
print("succeeded loading: {} for data set {} ".format(x, response['DataSet']['Name']))
except:
print("failed loading: {} ".format(x))

How to add username and name columns to pandas dataframe with search_all_tweets lookup in python

I am trying to collect tweets from 2022 using Twitter API. I can record the tweet_fields for the tweets, but I can't figure out how to add columns for the username and name (the user_fields) for each tweet.
I'm running the following code:
import requests
import os
import json
import tweepy
import pandas as pd
from datetime import timedelta
import datetime
bearer_token = "my_bearer_token_here"
keyword = "#WomeninSTEM"
start_time = "2022-01-01T12:01:00Z"
end_time = "2023-01-01T12:01:00Z"
client = tweepy.Client(bearer_token=bearer_token)
responses = client.search_all_tweets(query = "#WomeninSTEM", max_results= 500, start_time=start_time, end_time = end_time,
user_fields = ["username", "name"],
tweet_fields =["in_reply_to_user_id", "author_id", "lang",
"public_metrics", "created_at", "conversation_id"])
**##I can't get the username or name columns to work here.**
column = []
for i in range(len(responses.data)) :
row = []
Username = responses.data[i]["username"]
row.append(Username)
name = responses.data[i]["name"]
row.append(name)
text = responses.data[i].text
row.append(text)
favoriteCount = responses.data[i].public_metrics["like_count"]
row.append(favoriteCount)
retweet_count = responses.data[i].public_metrics["retweet_count"]
row.append(retweet_count)
reply_count = responses.data[i].public_metrics["reply_count"]
row.append(reply_count)
quote_count = responses.data[i].public_metrics["quote_count"]
row.append(quote_count)
created = responses.data[i].created_at
row.append(created)
ReplyTo = responses.data[i].text.split(" ")[0]
row.append(ReplyTo)
ReplyToUID = responses.data[i].in_reply_to_user_id
row.append(ReplyToUID)
ConversationID = responses.data[i]["conversation_id"]
row.append(ConversationID)
column.append(row)
data = pd.DataFrame(column)
Whenever I try and include username and name, I get this error:KeyError Traceback (most recent call last)
Assuming you're querying at https://api.twitter.com/2/tweets/[...], the response does not have a 'username' or a 'name' parameter, that's why you're getting a KeyError when trying to access them.
It does have an 'author_id' parameter, which you can use to perform an additional query at https://api.twitter.com/2/users/:id and retrieve 'username' and 'name'.
More info here and here.

How to perform operation on flask-admin database columns to store results in other column of same table

I am building flask admin app where I need to store total of couple of integer columns into third column of same table.
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView
from flask import Flask
import os
from flask_admin import Admin
application = Flask(__name__)
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir,"testing.db"))
application = Flask(__name__)
application.config["SQLALCHEMY_DATABASE_URI"] = database_file
application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
application.secret_key = "ssshhhh"
db = SQLAlchemy(application)
admin = Admin(application,name="FLASK")
class Test(db.Model):
id = db.Column("ID",db.Integer,primary_key=True)
first_no = db.Column("First_no",db.Integer)
second_no = db.Column("Second_no",db.Integer)
total = db.Column("Total",db.Integer)
class TestView(ModelView):
page_size = 20
edit_modal = True
if __name__ == '__main__':
db.create_all()
admin.add_view(TestView(Test, db.session))
application.run(debug=True)
Above example let me store values in all three fields manually which is not expected.
Expected result that I am looking for get total of couple of integers and stores in database as well.
Two options you can use:
Use the onupdate parameter of Column to set the value of total on update, for example:
total = db.Column("Total", db.Integer, onupdate=first_no + second_no)
Use a hybrid_property to calculated the total without storing the value:
class Test(db.Model):
...
#hybrid_property
def total(self):
return self.first_no + self.second_no

OperationalError no such table in Flask with SQLAlchemy

run.py
if __name__ == '__main__':
config()
app.run()
main.py
import database
app = Flask(__name__)
def config():
app.config.from_object('config.DevConfig')
# Run SQLAlchemy _that uses app.config_ and add entities if in DEBUG mode
database.init_db(app)
import blueprints.auth
app.register_blueprint(blueprints.auth.auth)
database.py
db = None
def init_db(app):
global db
db = SQLAlchemy(app)
from models import User, Interest, Event
if app.config['DEBUG']:
print 'Recreating all db'
db.create_all() # I DO create everything
print 'Loading test data'
... (here I add some Users and etc. and everything works fine - tests pass)
models.py
from database import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
...
blueprints/auth.py
from models import User
auth = Blueprint('auth', __name__)
#auth.route('/')
def index():
return str(User.query.get(1).interests)
And so I get
OperationalError: (OperationalError) no such table: user u'SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.passhash AS user_passhash, user.vk_page AS user_vk_page \nFROM user \nWHERE user.id = ?' (1,)
What am I doing wrong?
For anyone trying to use an in memory database:
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool
)
There were few things I had to change to make everything work.
replace DATABASE_URI with SQLALCHEMY_DATABASE_URI parametr in config
replace :memory: sqlite address with /tmp/test.db
Now it works fine.