本文整理汇总了Python中sqlalchemy.func.random函数的典型用法代码示例。如果您正苦于以下问题:Python random函数的具体用法?Python random怎么用?Python random使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了random函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: getTest
def getTest():
reload(sys)
sys.setdefaultencoding( "utf-8" )
question=models.WordQuize.query.order_by(func.random()).limit(20)
results=[]
results2=[]
results3=[]
#result={'user_id': 2,'s':1}
#{'id':+q.id,'question':+q.question,"option:":+q.option}
for q in question:
result={'id':q.id,'question':q.question,'option':q.option}
results.append(result)
question = models.ConfuseQuize.query.order_by(func.random()).limit(20)
for q in question:
result = {'id': q.id, 'question': q.question, 'option': q.option}
results3.append(result)
question=models.PhraseQuize.query.order_by(func.random()).limit(20)
for q in question:
result={'id':q.id,'question':q.question,'option':q.option}
results2.append(result)
json_result = {'result':results,'result2':results2, 'result3':results3}#json.dumps(json_result)
print results
print results2
print results3
return json.dumps(json_result,ensure_ascii=False)
开发者ID:xiaomino8,项目名称:test1,代码行数:25,代码来源:views.py
示例2: get_request
def get_request():
"""
@return: a random request guarantied to be locked and unique
"""
session = database.get_session()
me = Host.by_name(socket.gethostname(), session)
if me.region is not None:
# noinspection PyComparisonWithNone,PyPep8
query = session.query(HashRequest).join(HashRequest.host).join(Host.region).filter(
and_(HashRequest.locked == False, HashRequest.server != None,
Region.id == me.region.id)).order_by(func.random()).with_for_update()
else:
# noinspection PyComparisonWithNone,PyPep8
query = session.query(HashRequest).join(HashRequest.host).filter(
and_(HashRequest.locked == False, HashRequest.server != None,
HashRequest.host == me)).order_by(func.random()).with_for_update()
try:
request = query.first()
if request is None:
return None
request.locked = True
session.commit()
return request
except Exception as error:
session.rollback()
raise error
finally:
session.close()
开发者ID:konairius,项目名称:synctool,代码行数:29,代码来源:hasher.py
示例3: random
def random(self):
engine = str(db.engine)
if 'postgresql' in engine:
# Postgres
return Session.query(self).order_by(func.random()).first()
elif 'mysql' in engine:
# MySQL
return Session.query(self).order_by(func.rand()).first()
elif 'sqlite' in engine:
# sqlite
return Session.query(self).order_by(func.random()).first()
开发者ID:smeggingsmegger,项目名称:impression,代码行数:11,代码来源:mixin.py
示例4: test_generic_random
def test_generic_random(self):
assert func.random().type == sqltypes.NULLTYPE
assert isinstance(func.random(type_=Integer).type, Integer)
for ret, dialect in [
('random()', sqlite.dialect()),
('random()', postgresql.dialect()),
('rand()', mysql.dialect()),
('random()', oracle.dialect())
]:
self.assert_compile(func.random(), ret, dialect=dialect)
开发者ID:cpcloud,项目名称:sqlalchemy,代码行数:11,代码来源:test_functions.py
示例5: index
def index(self, **kw):
# items = DBSession.query(Item).all()
# my_page = Page(items, page = int(kw.get("page", 1)), url = lambda page:"%s?page=%d" % (self.request.path, page))
# self.render("index.html", my_page = my_page)
items = DBSession.query(Item).all()[:9]
try:
show_case1 = DBSession.query(Item).order_by(func.random()).all()[:4]
show_case2 = DBSession.query(Item).order_by(func.random()).all()[:4]
except:
show_case1 = DBSession.query(Item).order_by(func.rand()).all()[:4]
show_case2 = DBSession.query(Item).order_by(func.rand()).all()[:4]
self.render("index.html", items = items, show_case1 = show_case1, show_case2 = show_case2)
开发者ID:LamCiuLoeng,项目名称:dreamhouse,代码行数:12,代码来源:RootHandler.py
示例6: birdie_view
def birdie_view(request):
dbsession = DBSession()
userid = authenticated_userid(request)
user = dbsession.query(User).filter_by(userid=userid).first()
follows = dbsession.query(Follower).filter(Follower.follower == user.id)
follows = follows.order_by(Follower.follows.asc()).limit(10)
followers = dbsession.query(Follower).filter(Follower.follows == user.id)
followers = followers.order_by(Follower.follower.asc()).limit(10)
chirpers = [follow.follows for follow in follows]
chirpers.append(user.id)
chirps = dbsession.query(Chirp).filter(Chirp.author_id.in_(chirpers))
chirps = chirps.order_by(Chirp.timestamp.desc()).limit(30)
whomtofollow = dbsession.query(User).order_by(func.random()).limit(10)
return {
"app_url": request.application_url,
"static_url": request.static_url,
"userid": userid,
"user": user,
"elapsed": get_elapsed,
"follows": follows,
"followers": followers,
"user_chirps": False,
"whomtofollow": whomtofollow,
"chirps": chirps,
}
开发者ID:cguardia,项目名称:appsembler,代码行数:25,代码来源:views.py
示例7: get_representative_nodes
def get_representative_nodes():
"""Get elements with a reasonable distribution of node counts."""
step = 1000
start = 0
stop = 60000
limit = 50
record_names = ['name', 'gridcode', 'node_count']
ranges = []
to_process = []
s = Session()
while start < stop:
ranges.append([start, start + step])
start += step
for ctr, select_range in enumerate(ranges):
log.debug(select_range)
q = s.query(VectorProcessingUnit.name, Catchment.gridcode, Catchment.node_count).join(Catchment)
q = q.filter(Catchment.node_count >= select_range[0]).filter(Catchment.node_count < select_range[1])
q = q.order_by(func.random()).limit(limit)
for idx, record in enumerate(q):
to_process.append(dict(zip(record_names, record)))
s.close()
return to_process
开发者ID:logankarsten,项目名称:hydroRegrid,代码行数:30,代码来源:large_elements.py
示例8: rand
def rand(self, sender, *, orig_only=False):
''' A random tweet from someone.
Example::
/rand j
a random tweet from j
:param str sender: single sender
:param bool orig_only: original tweets only
:return: `Resp` object
:rtype: Resp
'''
sender = self._to_sender(sender)
assert len(sender) == 1, "so many people"
sender = sender[0]
cond = Tweet.user_id == int(sender)
if orig_only:
cond = cond & (Tweet.type == 'tweet')
one = self.session.query(Tweet).filter(cond)\
.order_by(func.random()).first()
if one is None:
return Resp(message="nothing indexed")
cmd = '/randt' if orig_only else '/rand'
keyboard = {"keyboard": [[cmd + ' ' + sender], ['/end']],
"selective": True, "resize_keyboard": True}
return Resp(message=self.fmt.format_rand(one),
keyboard=keyboard, markdown=True)
开发者ID:JoM-Lab,项目名称:JoM,代码行数:28,代码来源:query.py
示例9: get_random_mapobject_subset
def get_random_mapobject_subset(self, mapobject_type_name, n):
'''Selects a random subset of mapobjects.
Parameters
----------
mapobject_type_name: str
name of the selected
:class:`MapobjectType <tmlib.models.mapobject.MapobjectType>`
n: int
number of mapobjects that should be selected at random
Returns
-------
Tuple[int]
IDs of selected mapobject
'''
with tm.utils.ExperimentSession(self.experiment_id) as session:
mapobject_type = session.query(tm.MapobjectType.id).\
filter_by(name=mapobject_type_name).\
one()
mapobjects = session.query(tm.Mapobject.id).\
filter_by(mapobject_type_id=mapobject_type.id).\
order_by(func.random()).\
limit(n).\
all()
return [m.id for m in mapobjects]
开发者ID:dvischi,项目名称:TissueMAPS,代码行数:26,代码来源:base.py
示例10: meet_character
def meet_character(cls, character):
""" Get monster for character.
"""
return cls.query.filter(
cls.level >= character.level - 2,
cls.level <= character.level + 2
).order_by(func.random()).first()
开发者ID:EricSchles,项目名称:fquest,代码行数:7,代码来源:models.py
示例11: load_projects
def load_projects():
"""Takes 'n' the user specifies and returns n projects from the cluster."""
number = request.form.get("number")
print number
cluster_id = request.form.get("id")
print cluster_id
#returns n random projects in chosen cluster
cluster_query = modelsession.query(model.Cluster).filter(
model.Cluster.cluster_num==cluster_id).order_by(
func.random()).limit(number).all()
print len(cluster_query)
projects = []
#loops through projects in cluster_query to create a list of the project objs.
for item in cluster_query:
proj_id = item.project_id
proj_id = '"'+proj_id+'"'
print proj_id
query = modelsession.query(model.Project).filter(
model.Project.id==proj_id).first()
projects.append(query)
print projects
#creates a json object to pass to javascript
json_list = []
for i in range(len(projects)):
json_list.append({"id": projects[i].id,
"title": projects[i].title,
"location": projects[i].school.city + ", " +
projects[i].school.state,
"grade": projects[i].grade_level,
"needs": projects[i].fulfillment_trailer})
results = json.dumps(json_list)
return results
开发者ID:lzhou89,项目名称:ChoosyDonors,代码行数:32,代码来源:app.py
示例12: get
def get(self):
sort = request.args.get('sort')
role = request.args.get('role')
require = request.args.get('require')
limit = request.args.get('limit')
if sort == 'random':
users = User.query.order_by(func.random())
else:
users = User.query.order_by(desc(User.first_name))
if role:
roles = role.split(',')
users = users.filter(User.role.in_(roles))
if require:
# Return only users that have attributes that are lists with at least one element
# example, if require = 'host-applications', only return users with at least one host application
requires = require.split(',')
requires = [getattr(User, lisp_to_snake(require)).any() for require in requires]
users = User.query.filter(*requires)
if limit:
limit = int(limit)
users = users[:limit]
else:
users = users.all()
#print(row2dict(users[0]))
tmp = [row2dict(user) for user in users]
users = {'users': tmp}
return users
开发者ID:axelzcramer,项目名称:thoughtloungev2,代码行数:31,代码来源:views.py
示例13: update_scores
def update_scores(self, model, chunksize=10000):
# update node scores
waypoint_nodes = (
self.session.query(
Node,
ST_X(cast(Node.loc, Geometry)),
ST_Y(cast(Node.loc, Geometry)))
.filter(Node.num_ways != 0)
.order_by(func.random())) # random order
# process nodes in chunks for memory efficiency.
# note: normalization of scores is done per chunk, which should be a
# reasonable approximation to global normalization when the chunks are
# large since the query specifies random ordering
for chunk in _grouper(chunksize, waypoint_nodes):
nodes, x, y = zip(*chunk)
X = np.vstack((x, y)).T
scores = model.score_samples(X)
for node, score in zip(nodes, scores):
node.score = score
# update cumulative scores
sq = (
self.session.query(
Waypoint.id.label('id'),
func.sum(Node.score).over(
partition_by=Waypoint.way_id,
order_by=Waypoint.idx).label('cscore'))
.join(Node)
.subquery())
(self.session.query(Waypoint)
.filter(Waypoint.id == sq.c.id)
.update({Waypoint.cscore: sq.c.cscore}))
开发者ID:mcwitt,项目名称:scenicstroll,代码行数:35,代码来源:route_db.py
示例14: cmd
def cmd(send, msg, args):
"""Returns a random line from $nick.
Syntax: {command} (--channel <channel>) (nick)
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--channel', action=arguments.ChanParser)
parser.add_argument('nick', nargs='*')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
quote = args['db'].query(Log.msg, Log.source)
nick = ' '.join(cmdargs.nick) if cmdargs.nick else ""
if nick:
quote = quote.filter(Log.source == nick)
else:
quote = quote.filter(Log.source != args['botnick'])
target = cmdargs.channels[0] if hasattr(cmdargs, 'channels') else args['config']['core']['channel']
quote = quote.filter(or_(Log.type == 'pubmsg', Log.type == 'privmsg', Log.type == 'action'), Log.target == target,
func.length(Log.msg) > 5).order_by(func.random()).first()
if quote:
send("%s -- %s" % quote)
elif nick:
send("%s isn't very quotable." % nick)
else:
send("Nobody is very quotable :(")
开发者ID:tjcsl,项目名称:cslbot,代码行数:29,代码来源:line.py
示例15: get_question_bytag
def get_question_bytag(tag_name,limit):
"""
:param tag_name:
:return:
"""
print(tag_name)
max_questions=20
tag = models.Tag.query.filter_by(tag_name=tag_name).first()
if tag:
try:
limit = int(limit)
except Exception as e:
pass
if isinstance(limit,int):
if limit > max_questions or limit <=0:
limit=max_questions
questions = tag.quest.order_by(func.random()).limit(limit).all()
elif limit=='all':
questions = tag.quest.all()
else:
questions = []
if len(questions)==1:
r = questions[0].to_dict()
else:
r = [q.to_dict() for q in questions]
else:
r = []
return make_response(jsonify({"result":r}), 200)
开发者ID:web4innovation,项目名称:MobileAppSeveur,代码行数:29,代码来源:views.py
示例16: find
def find(self):
recipe = session.query(Recipe).filter(Recipe.done == False).order_by(func.random()).first()
if not recipe:
abort(500, message="Every recipe was done. Nice.")
recipe.done = True
session.commit()
return recipe
开发者ID:dommerq,项目名称:Recipes,代码行数:7,代码来源:daily.py
示例17: random
def random(self, n_instances=1, dialect=None):
"""Returns random model instances.
:param n_instances: the number of instances to return
:type n_instances: int
:param dialect: the engine dialect (the implementation of random differs
between MySQL and SQLite among others). By default will look up on the
query for the dialect used. If no random function is available for the
chosen dialect, the fallback implementation uses total row count to
generate random offsets.
:type dialect: str
:rtype: model instances
"""
if dialect is None:
dialect = self.session.get_bind().dialect.name
if dialect == 'mysql':
instances = self.order_by(func.rand()).limit(n_instances).all()
elif dialect in ['sqlite', 'postgresql']:
instances = self.order_by(func.random()).limit(n_instances).all()
else: # fallback implementation
count = self.count()
instances = [
self.offset(randint(0, count - 1)).first()
for _ in range(n_instances)
]
if len(instances) == 1:
return instances[0]
return instances
开发者ID:daqing15,项目名称:kit,代码行数:29,代码来源:orm.py
示例18: index
def index(request):
project_ids = [
r[0]
for r in (
request.db.query(Project.id)
.order_by(Project.zscore.desc().nullslast(), func.random())
.limit(5)
.all()
)
]
release_a = aliased(
Release,
request.db.query(Release)
.distinct(Release.project_id)
.filter(Release.project_id.in_(project_ids))
.order_by(
Release.project_id,
Release.is_prerelease.nullslast(),
Release._pypi_ordering.desc(),
)
.subquery(),
)
trending_projects = (
request.db.query(release_a)
.options(joinedload(release_a.project))
.order_by(func.array_idx(project_ids, release_a.project_id))
.all()
)
latest_releases = (
request.db.query(Release)
.options(joinedload(Release.project))
.order_by(Release.created.desc())
.limit(5)
.all()
)
counts = dict(
request.db.query(RowCount.table_name, RowCount.count)
.filter(
RowCount.table_name.in_(
[
Project.__tablename__,
Release.__tablename__,
File.__tablename__,
User.__tablename__,
]
)
)
.all()
)
return {
"latest_releases": latest_releases,
"trending_projects": trending_projects,
"num_projects": counts.get(Project.__tablename__, 0),
"num_releases": counts.get(Release.__tablename__, 0),
"num_files": counts.get(File.__tablename__, 0),
"num_users": counts.get(User.__tablename__, 0),
}
开发者ID:craig5,项目名称:warehouse,代码行数:60,代码来源:views.py
示例19: coverage
def coverage(self):
image = self.images.filter_by(is_coverage=True)
if image.count() == 0:
image = self.images.order_by(func.random()).limit(1)
image = image.first()
return image and {'url': image.url, 'id': image.id} or None
开发者ID:rudimk,项目名称:flamingo,代码行数:7,代码来源:models.py
示例20: get_quote
def get_quote(cls, id=None):
try:
if id is None:
return meta.session.query(cls).order_by(func.random()).limit(1).one()
return meta.session.query(cls).get(id)
except:
meta.session.rollback()
raise
开发者ID:jeremysmitherman,项目名称:Hoggy2,代码行数:8,代码来源:quote.py
注:本文中的sqlalchemy.func.random函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论