您好我很难想到如何在localhost管理数据库视图中从sqlalchemy中选择一个随机行。我希望它选择一个随机列表,但是那些用户已分配,因此它选择一个随机抽奖,如颜色:Ruby up1:dgg2 up2:fh73.below是本地主机数据库会话和代码的代码。在modelview localhost中查看数据库。
admin = Admin(app, name='raffles', template_mode='bootstrap3')
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Raffle, db.session))
我需要帮助添加代码以从那里选择抽奖
继承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)
并且继承了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
答案 0 :(得分:0)
使用MySQL选择一个随机行:
SELECT column FROM table
ORDER BY RAND()
LIMIT 5
选择IBM DB2的随机行
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
使用Microsoft SQL Server选择随机行:
SELECT TOP 5 column FROM table
ORDER BY NEWID()
使用Oracle选择随机记录:
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 5
使用PostgreSQL选择一个随机行:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 5
使用SQLite选择随机行:
SELECT column FROM table
ORDER BY
RANDOM() LIMIT 5;