def index_dashboard(): saldo_total = db.session.query(db.func.sum(Movimento.saldo)).filter( Movimento.user_id == session.get('user_id')).first()[0] or 0.0 ultima_saida = Saida.query.order_by(db.desc(Saida.created_at)).filter( Movimento.user_id == session.get('user_id')).first() ultima_entrada = Entrada.query.order_by(db.desc( Entrada.created_at)).filter( Movimento.user_id == session.get('user_id')).first() movimentos = Movimento.query.order_by(db.desc( Movimento.created_at)).filter( Movimento.user_id == session.get('user_id')).limit(8).all() saida_total = db.session.query(db.func.sum(Saida.valor)).filter( Movimento.user_id == session.get('user_id')).first()[0] saidas_categoria = db.session.execute(f""" select categoria.titulo, sum(saida.valor) from saida inner join categoria on categoria.id = saida.categoria_id where categoria.user_id = {session.get('user_id')} group by saida.categoria_id, categoria.titulo """) ctx = { 'saldo_total': saldo_total, 'ultima_saida': ultima_saida, 'ultima_entrada': ultima_entrada, 'movimentos': movimentos, 'saida_total': saida_total, 'saidas_categoria': saidas_categoria } return render_template('dashboard/index.html', **ctx)
def projectList(): user_id = session.get('user_id') status = request.values.get("status") if not status: status = 3 if status != 3: projectList = Project.query.filter( db.and_(Project.status == status)).order_by( db.desc(Project.add_time)).all() else: projectList = Project.query.order_by(db.desc(Project.add_time)).all() content = [] if projectList: for item in projectList: caseCount = Sample.query.filter( db.and_(Sample.project_id == item.id)).count() row_data = users.query.filter(db.and_(users.id == user_id)).first() username = "" if row_data: username = row_data.username content.append({ "id": item.id, "name": item.name, "add_time": item.add_time.strftime('%Y-%m-%d %H:%M:%S'), "add_user": username, "count": caseCount, "status": item.status, }) return make_response(jsonify({'code': 0, 'msg': '', 'content': content}))
def load_admin(): search_text = request.args.get('search_text', '') page_size = int(request.args.get('page_size', '10')) page_number = int(request.args.get('page_number', '1')) sort_name = request.args.get('sort_name', 'number') sort_order = request.args.get('sort_order', 'asc') if search_text == '': if sort_order == 'asc': pagination = Admin.query.order_by(db.asc(Admin.id)).paginate( page_number, page_size, False) else: pagination = Admin.query.order_by(db.desc(Admin.id)).paginate( page_number, page_size, False) else: if sort_order == 'asc': pagination = Admin.query.order_by(db.asc(Admin.id)).paginate( page_number, page_size, False) else: pagination = Admin.query.order_by(db.desc(Admin.id)).paginate( page_number, page_size, False) admins = [] for item in pagination.items: admins.append({ 'id': item.id, 'user_name': item.user_name, 'create_time': item.create_time.strftime("%Y-%m-%d") if item.create_time else None }) return json.dumps({"total": pagination.total, "rows": admins})
def get_active_posts(mode=None): orders = { 'recent': (db.desc(Post.time), ), 'popular': (db.desc('commentCount'), db.desc(Post.time)), 'best': (db.desc('likeCount'), db.desc(Post.time)), 'early': (db.asc(Post.time), ) } order = orders.get(mode, orders['recent']) likes = db.select([db.func.count(Vote.id)]).where( db.and_(Vote.value == 1, Vote.post_id == Post.id)).as_scalar().label('likeCount') dislikes = db.select([db.func.count(Vote.id)]).where( db.and_(Vote.value == -1, Vote.post_id == Post.id)).as_scalar().label('dislikeCount') comments = db.select([ db.func.count(Comment.id) ]).where(Comment.post_id == Post.id).as_scalar().label('commentCount') return filter_by_active_posts( Post.query.with_entities(Post, likes, dislikes, comments)).order_by(*order)
def detail(user_id): user = User.query.filter_by(id=user_id).first() stories = user.stories.order_by(db.desc("created")).limit(5) comments = user.comments.order_by(db.desc("created")).limit(5) return render_template("users/detail.html", user=user, stories=stories, comments=comments)
def index(page=1): posts = Rubbish.query.filter_by(user_id=current_user.id).order_by( db.desc(Rubbish.time)).paginate(page, 3, False) messages = Punish.query.filter_by(to_user=current_user.username).order_by( db.desc(Punish.time)).paginate(page, 3, False) return render_template('index.html', title='Home', posts=posts, messages=messages)
def user(username, page=1): user = User.query.filter_by(username=username).first() posts = Rubbish.query.filter_by(user_id=user.id).order_by( db.desc(Rubbish.time)).paginate(page, 3, False) messages = Punish.query.filter_by(to_user=user.username).order_by( db.desc(Punish.time)).paginate(page, 3, False) return render_template('user.html', user=user, posts=posts, messages=messages)
def load_student(): search_text = request.args.get('search_text', '') page_size = int(request.args.get('page_size', '10')) page_number = int(request.args.get('page_number', '1')) sort_name = request.args.get('sort_name', 'number') sort_order = request.args.get('sort_order', 'asc') if search_text == '': if sort_order == 'asc': pagination = Student.query.order_by(db.asc( Student.number)).paginate(page_number, page_size, False) else: pagination = Student.query.order_by(db.desc( Student.number)).paginate(page_number, page_size, False) else: if sort_order == 'asc': pagination = Student.query.order_by(db.asc( Student.number)).paginate(page_number, page_size, False) else: pagination = Student.query.order_by(db.desc( Student.number)).paginate(page_number, page_size, False) students = [] for item in pagination.items: students.append({ 'number': item.number, 'name': item.name, 'signature': item.signature, 'age': item.age, 'sex': item.sex, 'entrance_year': item.entrance_year, 'classes_id': item.classes_id, 'class': item.classes.name, 'college': item.college.name, 'college_id': item.college_id, 'birth_day': item.birth_day.strftime("%Y-%m-%d") if item.birth_day else None, 'head_url': item.head_url, 'telephone': item.telephone, 'mail': item.mail, }) return json.dumps({"total": pagination.total, "rows": students})
def taskList(): user_id = session.get('user_id') taskType = request.json.get("taskType") pageNum = request.json.get("pageNum") dataCount = Task.query.filter(db.and_( Task.task_type == taskType, )).count() top_task = Task.query.filter( db.and_(Task.task_type == taskType, Task.name.like("%置顶%"))).order_by( db.desc(Task.add_time)).all() if pageNum: listData = Task.query.filter( db.and_(Task.task_type == taskType, Task.name.notlike("%置顶%"))).order_by(db.desc( Task.add_time)).slice((pageNum - 1) * 20, pageNum * 20).all() else: listData = Task.query.filter( db.and_(Task.task_type == taskType, Task.name.notlike("%置顶%"))).order_by(db.desc( Task.add_time)).all() content = { 'taskContent': [], 'total': dataCount, } listData = top_task + listData for task in listData: row_data = users.query.filter( db.and_(users.id == task.user_id)).first() username = "" if row_data: username = row_data.username update_time = "" if task.update_time: update_time = task.update_time.strftime('%Y-%m-%d %H:%M:%S') content['taskContent'].append({ "id": task.id, "name": task.name, "runTime": task.run_time, "add_time": task.add_time.strftime('%Y-%m-%d %H:%M:%S'), "add_user": username, "update_time": update_time, "status": task.status, }) return make_response(jsonify({'code': 0, 'content': content, 'msg': u''}))
def get_connect(message): taskType = message['taskType'] pageNum = message['pageNum'] dataCount = Task.query.filter(db.and_( Task.task_type == taskType, )).count() top_task = Task.query.filter( db.and_(Task.task_type == taskType, Task.name.like("%置顶%"))).order_by( db.desc(Task.add_time)).all() if pageNum: listData = Task.query.filter( db.and_(Task.task_type == taskType, Task.name.notlike("%置顶%"))).order_by(db.desc( Task.add_time)).slice((pageNum - 1) * 20, pageNum * 20).all() else: listData = Task.query.filter( db.and_(Task.task_type == taskType, Task.name.notlike("%置顶%"))).order_by(db.desc( Task.add_time)).all() content = { 'taskContent': [], 'total': dataCount, } listData = top_task + listData for task in listData: row_data = users.query.filter( db.and_(users.id == task.user_id)).first() username = "" if row_data: username = row_data.username update_time = "" if task.update_time: update_time = task.update_time.strftime('%Y-%m-%d %H:%M:%S') content['taskContent'].append({ "id": task.id, "name": task.name, "runTime": task.run_time, "add_time": task.add_time.strftime('%Y-%m-%d %H:%M:%S'), "add_user": username, "update_time": update_time, "status": task.status, }) return content
def get(self): index = parser.parse_args()['order'] ##sort user_id = parser.parse_args()['user_id'] pos = parser.parse_args()['pos'] ##filter if not index: index = 1 if not pos: pos = 0 if index not in range(-3, 4) or pos not in range(6): return rMessage(error=State.ArgError).response order = [PlayerBase.id, PlayerBase.id, PlayerBase.score, PlayerBase.price] poss = ['', 'c', 'f', 'f', 'g', 'g'] PB = PlayerBase res = query(PB.id, PB.name, PB.pos1, PB.pos2, PB.price, PB.score, PB.team_id) if pos != 0: res = res.filter((PB.pos1 == poss[pos]) | (PB.pos2 == poss[pos])) if abs(index) == 1 and Recom.recom: pl = Recom.recom.sortRecommend(user_id) print('recom list') pinfo = {p[0]: p for p in res.all()} ##id-tuple res = [pinfo[p] for p in pl if p in pinfo] ##tuple list else: res = res.order_by(db.desc(order[abs(index)])).all() if index <= 0: return rMessage([{"id": p[0], "name": p[1], "pos1": p[2], "pos2": p[3], "price": p[4], "score": p[5]} for p in res]).response else: return rMessage([p[0] for p in res]).response
def get_twitter_for_acc(account): consumer_key = app.config['TWITTER_CONSUMER_KEY'] consumer_secret = app.config['TWITTER_CONSUMER_SECRET'] tokens = (OAuthToken.query.with_parent(account).order_by( db.desc(OAuthToken.created_at)).all()) for token in tokens: t = Twitter(auth=OAuth(token.token, token.token_secret, consumer_key, consumer_secret)) try: t.account.verify_credentials() return t except TwitterHTTPError as e: if e.e.code == 401: # token revoked if sentry: sentry.captureMessage('Twitter auth revoked', extra=locals()) db.session.delete(token) db.session.commit() else: raise TemporaryError(e) except URLError as e: raise TemporaryError(e) raise TemporaryError("No access to account {}".format(account))
def post(self): # 得到参数列表 args = parse.parse_args() # 找到之前最大的id max = models.activityModel.query.order_by( db.desc(models.activityModel.id)).first() id = max.id + 1 if max else 1 # 创建活动模板 activityModel = models.activityModel() # 将传入参数加入到activityModel中 activityModel.id = id activityModel.name = args.name activityModel.time1 = args.time1 activityModel.activity1 = args.activity1 activityModel.time2 = args.time2 activityModel.activity2 = args.activity2 activityModel.time3 = args.time3 activityModel.activity3 = args.activity3 # 将activityModel存入数据库 try: db.session.add(activityModel) db.session.commit() except Exception as e: db.session.rollback() abort(500)
def postlist(): message = dict(MESSAGE) reqp = reqparse.RequestParser() reqp.add_argument("page", type=int, required=True, location=["json", "form"]) args = reqp.parse_args() article = Article.query.filter(Article.privacy==0).order_by(db.desc(Article.id)).\ paginate(args["page"], per_page=5, error_out=False) article_list = [] for item in article.items: article_list.append({ "id": item.id, "datetime": month[item.p_month - 1] + " " + str(item.p_day) + ", " + str(item.p_year), "title": item.title, "tags": item.tags.split("丨") }) message["res"] = {"postlist": article_list, "totalpage": article.pages} return jsonify(message)
def category(category_name): posts = Category.get_item_by_name(category_name).posts.filter( Post.post_date <= datetime.now()).order_by(db.desc( Post.post_date)).paginate(1, 10, True) return render_template('home.html', posts=posts, title='Category: ' + category_name)
def post(self): # 找到之前最大的id max = models.plan.query.order_by(db.desc(models.plan.id)).first() id = max.id + 1 if max else 1 plan = models.plan() args = parse.parse_args() plan.id = id plan.name = args.name plan.key = getKey(id) plan.wechat = args.wechat plan.date = args.date # 更改用户的参与方案 user = models.user.query.get(args.wechat) if user: user.plan_id = id else: return { abort(400, message="user {} doesn't exist".format(args.wechat)) } # 生成识别码 try: db.session.add(plan) db.session.commit() return {"message": True} except Exception as e: db.session.rollback() abort(500)
def job_log_all_list(): keywords = request.args.to_dict() page = int(request.args.get('page') or 1) filter_arr = [] task_name = keywords.get('task_name') if task_name: filter_arr.append(CronInfos.task_name.like('{}%'.format(task_name))) beg_time = keywords.get('beg_time') end_time = keywords.get('end_time') if beg_time and end_time: filter_arr.append(JobLog.create_time.between(beg_time, end_time)) page_data = JobLog.query.\ join(CronInfos,CronInfos.id == JobLog.cron_info_id).\ filter(*filter_arr).\ order_by(db.desc(JobLog.id)).\ add_entity(CronInfos).\ paginate(page=page,per_page=20) if 'page' in keywords: del keywords['page'] return render_template("job_log_all_list.html", page_data=page_data, keywords=keywords)
def post(self): # 找到之前最大的id max = models.planSouvenir.query.order_by( db.desc(models.planSouvenir.id)).first() id = max.id + 1 if max else 1 args = parse.parse_args() plan = models.plan.query.filter_by(id=args.plan).first() planSouvenir = models.planSouvenir() planSouvenir.id = id planSouvenir.plan = args.plan planSouvenir.souvenir = args.souvenir if plan: if args.wechat == plan.wechat: if models.planSouvenir.query.filter_by( plan=args.plan, souvenir=args.souvenir).first(): abort(400, message="{} souvenir existed".format(args.souvenir)) else: try: db.session.add(planSouvenir) db.session.commit() return {"message": True} except Exception as e: db.session.rollback() abort(500) else: return {"message": "please call the source"}, 200 else: return {"message": "no this plan"}, 400
class Post(db.Model, TimestampMixin, RemoteIDMixin): __tablename__ = 'posts' id = db.Column(db.String, primary_key=True) author_id = db.Column(db.String, db.ForeignKey('accounts.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False) author = db.relationship(Account, foreign_keys=(author_id, ), backref=db.backref( 'posts', order_by=lambda: db.desc(Post.created_at))) favourite = db.Column(db.Boolean, server_default='FALSE', nullable=False) has_media = db.Column(db.Boolean, server_default='FALSE', nullable=False) direct = db.Column(db.Boolean, server_default='FALSE', nullable=False) favourites = db.Column(db.Integer) reblogs = db.Column(db.Integer) is_reblog = db.Column(db.Boolean, server_default='FALSE', nullable=False) def __str__(self): return '<Post ({}, Author: {})>'.format(self.id, self.author_id)
def get_book_last_rent_time(id): last_rent = Rentals.query.filter_by(book_id=id).order_by( db.desc(Rentals.rented_at)).first() if last_rent: if not last_rent.returned: return datetime.strftime(last_rent.rented_at, "%d/%m/%y") return None
def list_nicknames(): nicks = Nickname.query\ .with_entities(Nickname.id, Nickname.nickname, func.count(links.c.link_id.distinct()).label('count'))\ .join(links, (Nickname.id == links.c.nickname_id))\ .group_by(Nickname.id)\ .order_by(db.desc('count')).all() return nicks
def taskList(): user_id = session.get('user_id') taskType = request.json.get("taskType") listData = Task.query.filter(db.and_( Task.task_type == taskType, )).order_by(db.desc(Task.add_time)).all() content = [] for task in listData: row_data = users.query.filter( db.and_(users.id == task.user_id)).first() username = "" if row_data: username = row_data.username update_time = "" if task.update_time: update_time = task.update_time.strftime('%Y-%m-%d %H:%M:%S') content.append({ "id": task.id, "name": task.name, "runTime": task.run_time, "taskDesc": task.task_desc, "add_time": task.add_time.strftime('%Y-%m-%d %H:%M:%S'), "add_user": username, "update_time": update_time, "status": task.status, }) return make_response(jsonify({'code': 0, 'content': content, 'msg': u''}))
def index(page): pagination = Post.query.order_by( db.desc(Post.timestamp) ).paginate(page, INDEX_PER_PAGE, False) return render_template('index.html', title='Home', pagination=pagination)
def index_addition(): # 声明全局变量 global index_add_counter posts = [] tags = defaultdict(list) # 根据加载次数计算相对post_id for post_id in range(10 * index_add_counter + 1, 10 * index_add_counter + 11): # tags.setdefault(int, []) try: post = db.session.query(Post).order_by(db.desc(Post.id))[post_id - 1] posts.append(post) for tag_id in (db.session.query(PostTagRel).filter(PostTagRel.id == post.id).first().tag_id.split(',')): tag = db.session.query(Tag).filter(Tag.tag_id == tag_id).first().tag_name tags[post.id].append(tag) except IndexError: # posts.reverse() index_add_counter += 1 return render_template('index-addition.html', title = 'Home', user = user, posts = posts, tags = tags) # posts.reverse() index_add_counter += 1 return render_template('index-addition.html', title = 'Home', user = user, posts = posts, tags = tags) #对给定模板传递参数,并翻译模板
def get_years(): years = Post.active_posts \ .group_by('years') \ .order_by(db.desc(Post.time)) \ .values(db.func.year(Post.time).label('years')) return list(zip(*years)).pop()
def gen_wordstat_query(request): q = db.session.query(WordStat, # Word.word_pos, # Word.word, Word, db.func.sum(WordStat.freq).label('freq')) q = q.join(Word) q = q.join(Source) q = q.outerjoin(En_Rus) args = clean_args(request, 'src') if args: q = q.filter(WordStat.source_id.in_(args)) args = clean_args(request, 'tag') if args: sq = db.session.query(sources_tags.columns.source_id) sq = sq.filter(sources_tags.columns.tag_id.in_(args)) sq = sq.subquery() q = q.filter(Source.source_id.in_(sq)) args = clean_args(request, 'pos') if args: q = q.filter(Word.word_pos.in_(args)) args = clean_args(request, 'trn') if args: if args[0] == '1': q = q.filter(En_Rus.translation != None) elif args[0] == '0': q = q.filter(En_Rus.translation == None) args = clean_args(request, 'freq') if args: q = q.filter(Word.freq_index.in_(args)) q = q.group_by(WordStat.word_id, Word.word_pos, Word.word) q = q.order_by(db.desc('freq')) return q
def post(self, id): # # 判断纪念品是否存在 # if models.souvenir.query.get(id): # abort(400, message="{} existed".format(id)) # 找到之前最大的id max = models.souvenir.query.order_by(db.desc( models.souvenir.id)).first() id = max.id + 1 if max else 1 # 创建纪念品 souvenir = models.souvenir() souvenir.id = id args = parse.parse_args() # 将传入参数加入到souvenir中 souvenir.name = args.name souvenir.introduce = args.introduce souvenir.picture = args.picture # 将souvenir存入数据库 try: db.session.add(souvenir) db.session.commit() return {"message": True} except Exception as e: db.session.rollback() abort(500)
def get_school_dynamic(): cur_page = int(request.args.get("page")) pagination = Dynamics.query.filter(Dynamics.type == '0').order_by( db.desc(Dynamics.add_time)).paginate(cur_page, 20, False) has_next_page = (False if pagination.page == pagination.pages else True) data = format_dynamic(pagination.items) return json.dumps({"has_next_page": has_next_page, "data": data})
def addCase(): user_id = session.get('user_id') id = request.json.get("id") name = request.json.get("name") try: project_id = Tree.query.filter_by(id=id).first().project_id index_id = Tree.query.filter( db.and_(Tree.project_id == project_id, )).order_by( db.desc(Tree.index_id)).first().index_id data = Tree(project_id, id, name, 2, user_id, index_id + 1) db.session.add(data) db.session.commit() return make_response( jsonify({ 'code': 0, 'content': { "id": data.id }, 'msg': u'新建成功!' })) except Exception, e: print e return make_response( jsonify({ 'code': 10002, 'content': None, 'msg': u'新建失败!' }))
class TwitterArchive(db.Model, TimestampMixin): __tablename__ = 'twitter_archives' id = db.Column(db.Integer, primary_key=True) account_id = db.Column(db.String, db.ForeignKey('accounts.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) account = db.relationship(Account, backref=db.backref( 'twitter_archives', order_by=lambda: db.desc(TwitterArchive.id))) body = db.deferred(db.Column(db.LargeBinary, nullable=False)) chunks = db.Column(db.Integer) chunks_successful = db.Column(db.Integer, server_default='0', nullable=False) chunks_failed = db.Column(db.Integer, server_default='0', nullable=False) def status(self): if self.chunks is None or self.chunks_failed > 0: return 'failed' if self.chunks_successful == self.chunks: return 'successful' return 'pending'
def comments(story_id): story = Story.query.filter_by(id=story_id).first() return paginate( request, Comment.query.order_by( db.desc("created")).filter_by(story_id=story_id), 50, "stories/comments.html")
def post(self, id): # # 判断房间是否存在 # if models.hotelRoom.query.get(id): # abort(400, message="{} existed".format(id)) # 找到之前最大的id max = models.hotelRoom.query.order_by(db.desc( models.hotelRoom.id)).first() id = max.id + 1 if max else 1 # 创建房间 hotelRoom = models.hotelRoom() hotelRoom.id = id args = parse.parse_args() # 将传入参数加入到hotelRoom中 hotelRoom.hotel = args.hotel hotelRoom.name = args.name hotelRoom.introduce = args.introduce hotelRoom.picture = args.picture # 将hotelRoom存入数据库 try: db.session.add(hotelRoom) db.session.commit() return {"message": True} except Exception as e: db.session.rollback() abort(500)
def post(self): # 得到参数列表 args = parse.parse_args() # 找到之前最大的id max = models.auction.query.order_by(db.desc(models.auction.id)).first() id = max.id + 1 if max else 1 # 创建拍卖物品 auction = models.auction() # 将传入参数加入到auction中 auction.id = id auction.name = args.name auction.address = args.address auction.date = args.date auction.picture1 = args.picture1 auction.picture2 = args.picture2 auction.picture3 = args.picture3 auction.introduce = args.introduce auction.money = 0 auction.paid = 0 # 将auction存入数据库 try: db.session.add(auction) db.session.commit() return {"message": "success"} except Exception as e: db.session.rollback() abort(500)
def comment(name=''): comments_list = [] have_nickname = set() name = name comments = Comment.query.filter(Comment.movie_name == name).order_by(db.desc(Comment.usednum)).limit(60).all() if len(comments) < 10: new_comments = Comment.query.limit(60 - len(comments)).all() comments.extend(new_comments) for item in comments: if item.nickname not in have_nickname: comment = {} comment['name'] = item.movie_name comment['id'] = item.id comment['nickname'] = item.nickname comment['usefulnum'] = item.usednum comment['uselessnum'] = item.unusednum comment['responsenum'] = item.responsenum comment['time'] = item.time comment['avatar'] = item.avatar comment['content'] = item.content comments_list.append(comment) have_nickname.add(item.nickname) if len(comments_list) >= 20: break return render_template('comment.html', comments=comments_list)
def estimate_eligible_for_delete(self): """ this is an estimation because we do not know if favourite status has changed since last time a post was refreshed and it is unfeasible to refresh every single post every time we need to know how many posts are eligible to delete """ latest_n_posts = (Post.query.with_parent(self, 'posts').order_by( db.desc(Post.created_at)).limit(self.policy_keep_latest)) query = (Post.query.with_parent( self, 'posts').filter(Post.created_at <= db.func.now() - self.policy_keep_younger).except_(latest_n_posts)) if (self.policy_keep_favourites != 'none'): query = query.filter( db.or_( Post.favourite == ( self.policy_keep_favourites == 'deleteonly'), Post.is_reblog)) if (self.policy_keep_media != 'none'): query = query.filter( db.or_( Post.has_media == (self.policy_keep_media == 'deleteonly'), Post.is_reblog)) if (self.policy_keep_direct): query = query.filter(~Post.direct) return query.count()
def get(self, assembly_id): args = self.reqparse.parse_args() contigs = user_assembly_or_404(assembly_id).contigs # Column loading fields = args.fields.split(',') if args.coverages: fields.append('coverage') if args.pca: fields.extend(['pc_1', 'pc_2', 'pc_3']) contigs = contigs.options(db.load_only(*fields)) # Sort if args.sort: order = db.desc(args.sort[1:]) if args.sort[0] == '-' else db.asc(args.sort) contigs = contigs.order_by(order) # Filters if args.length: for value in args.length: filter = filter_contigs(Contig.length, value) contigs = contigs.filter(filter) if args.gc: for value in args.gc: filter = filter_contigs(Contig.gc, value) contigs = contigs.filter(filter) if args.bins: contigs = contigs.options(db.joinedload('bins')) bin_ids = args.bins.split(',') contigs = contigs.join((Bin, Contig.bins)).filter(Bin.id.in_(bin_ids)) # Load in pagination contig_pagination = contigs.paginate(args.index, args._items, False) result = [] for i, contig in enumerate(contig_pagination.items): r = {} if args.fields: for field in fields: if field != 'coverage': r[field] = getattr(contig, field) if args.coverages: r.update(contig.coverages) if args.pca: r['pc_1'], r['pc_2'], r['pc_3'] = contig.pc_1, contig.pc_2, contig.pc_3 if args.colors: for bin in contig.bins: r['color_{}'.format(bin.bin_set_id)] = bin.color if args.bins: r['bin'] = [b.id for b in contig.bins if str(b.id) in bin_ids][0] result.append(r) return { 'contigs': result if args.contigs else [], 'indices': contig_pagination.pages, 'index': args.index, 'count': contigs.count(), 'items': args._items }
def user(nickname, page = 1): user = User.query.filter_by(nickname = nickname).first() if user == None: flash('User ' + nickname + ' not found.') return redirect(url_for('index')) posts = user.posts.order_by(db.desc(Post.timestamp)).paginate(page, POSTS_PER_PAGE, False) return render_template('user.html', user = user, posts = posts)
def find_all(offset=None, limit=None): """ Get all galleries """ query = db.session.query(User).\ order_by(db.desc(User.name)) if offset is not None and limit is not None: query = query.limit(limit).\ offset(offset) return query.all()
def find_all(offset, limit, search_query): """ Get all galleries """ query = db.session.query(Gallery) if search_query is not None: query = query.filter(func.lower(Gallery.name).like('%%%s%%' % search_query)) return query.order_by(db.desc(Gallery.created)).\ limit(limit).\ offset(offset).\ all()
def _contents(): categories = Category.query.all() query = db.session.query(Tag, db.func.count(Post.id)).join(Post.tags).group_by(Tag.id).order_by( db.desc(db.func.count(Post.id))) tags = query.all() year_func = extract('year', Post.publish_date) month_func = extract('month', Post.publish_date) archives = db.session.query(year_func, month_func, func.count(Post.id)).group_by(year_func).group_by( month_func).all() recent_posts = Post.query.order_by(Post.publish_date.desc()).limit(5).all() return {'categories': categories, 'tags': tags, 'archives': archives, 'recent_posts': recent_posts}
def archives(): posts = db.session.query(Post).order_by(db.desc(Post.id)).all() # 获取键为tag_id,值为对应标签的文章的列表的字典 tag_posts = defaultdict(list) for i in range(1, db.session.query(Tag).count()+1): # s = db.session.query(PostTagRel).filter((PostTagRel.tag_id).like('6%')).all() tag_posts[i] = db.session.query(Post).join(PostTagRel).filter((PostTagRel.tag_id).like(str(i) + '%')).all() # dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True) return render_template('archives.html', title = 'archives.html', posts = posts, tag_posts = tag_posts)
def users(user_id, page): form = AboutMeForm() if user_id != current_user.id: flash('Sorry, you can only view your profile!', 'error') return redirect('/index') #blogs = user.posts.paginate(page, PER_PAGE, Flase).items pagination = Post.query.filter_by(user_id = current_user.id).order_by( db.desc(Post.timestamp)).paginate(page, PER_PAGE, False) return render_template('user.html',form=form,pagination=pagination)
def all(self, offset=None, limit=None, order_by=None, desc=False): query = self.__model__.query if order_by is not None: if desc: query = query.order_by(db.desc(order_by)) else: query = query.order_by(order_by) if offset is not None: query = query.offset(offset) if limit is not None: query = query.limit(limit) return query.all()
def get(self): t = datetime.utcnow() show = Message.query.order_by(db.desc(Message.time)).limit(10).all() mlist = [] for mess in show: f = mess.timedel(t) r = { 'key':mess.id, 'sender':mess.sender, 'message':mess.content, 'time': mess.time.strftime("at %I:%M%p") } mlist.append(r) return mlist,210,{'Access-Control-Allow-Origin':'*'}
def users(user_id, page): form = AboutMeForm() if user_id != current_user.id: flash("Sorry, you can only view your profile!", "error") return redirect("/index") # pagination = user.posts.paginate(page, PER_PAGE, False).items pagination = Post.query.filter_by( user_id = current_user.id ).order_by( db.desc(Post.timestamp) ).paginate(page, PER_PAGE, False) return render_template( "user.html", form=form, pagination=pagination)
def _move(self, parent_id, pos): branch = self _parent_id = branch.parent_id # find out if the position of moving is the same. If it is so then do nothing if ( (parent_id == None or parent_id == _parent_id) and pos != -1 ): curpos = branch.parent.get_subbs().index(branch) if ( curpos == pos ): return if ( parent_id != None ): _parent_id = parent_id if pos == -1: lowestb = db.session.query(Branch).filter_by(parent_id = _parent_id).order_by(db.desc('orderb')).first() if ( lowestb == None ): branch.orderb = app.general.orderb_step # start numeration from begining else: if lowestb.orderb >= app.general.orderb_MAX : self._reindexing_orderb(_parent_id) branch.move(_parent_id, pos) return branch.orderb = lowestb.orderb + app.general.orderb_step elif pos >= 0: leftNeigh = 0 if pos > 0: leftNeighB = db.session.query(Branch).filter_by(parent_id = _parent_id).order_by('orderb').offset(pos-1).limit(1).first() leftNeigh = leftNeighB.orderb # if the branch is moved down we have to increment pos (to ommit the branch) if leftNeigh >= branch.orderb : pos += 1 leftNeighB = db.session.query(Branch).filter_by(parent_id = _parent_id).order_by('orderb').offset(pos-1).limit(1).first() leftNeigh = leftNeighB.orderb rightNeighB = db.session.query(Branch).filter_by(parent_id = _parent_id).order_by('orderb').offset(pos).limit(1).first() rightNeigh = rightNeighB.orderb addit = (rightNeigh - leftNeigh) / 2 if int(addit) <= 1: self._reindexing_orderb(_parent_id) branch.move(_parent_id, pos) return branch.orderb = int(leftNeigh + addit) else: raise NegativePosition(connection=db.session) if _parent_id : par = branch.parent branch.parent_id = _parent_id self.set_main(self.main)
def to_object(self): """ Get it as an object """ photos = db.session.query(Photo)\ .filter(Photo.gallery_id == self.id)\ .order_by(db.asc(Photo.created), db.desc(Photo.name)) gallery = { "id": self.id, "name": self.name, "folder": self.folder, "share_code": self.share_code, "modified": self.modified.strftime('%Y-%m-%d %H:%M:%S'), "created": self.created.strftime('%Y-%m-%d %H:%M:%S'), "photos": [photo.to_object() for photo in photos] } return gallery
def get(self, contigset_id): args = self.reqparse.parse_args() contigs = user_contigset_or_404(contigset_id).contigs if args.fields: fields = args.fields.split(',') contigs = contigs.options(db.load_only(*fields)) if args.sort: order = db.desc(args.sort[1:]) if args.sort[0] == '-' else db.asc(args.sort) contigs = contigs.order_by(order) if args.length: length = args.length.rstrip('-').rstrip('+') if not length.isnumeric(): return length = int(length) if args.length.endswith('-'): filter = Contig.length < length elif args.length.endswith('+'): filter = Contig.length > length else: filter = Contig.length == length contigs = contigs.filter(filter) if args.bins: bin_ids = args.bins.split(',') contigs = contigs.join((Bin, Contig.bins)).filter(Bin.id.in_(bin_ids)) if args.coverages: contigs = contigs.options(db.joinedload('coverages')) contig_pagination = contigs.paginate(args.index, args._items, False) result = [] for contig in contig_pagination.items: r = {} if args.fields: for field in fields: r[field] = getattr(contig, field) if args.coverages: for cov in contig.coverages: r[cov.name] = cov.value result.append(r) return {'contigs': result, 'indices': contig_pagination.pages, 'index': args.index, 'count': contigs.count(), 'items': args._items}
def user(user_id, page): # userid is got by url form = AboutMeForm() user = User.query.filter(User.id == user_id).first() # get user from database if not user: # not find the user required flash("您访问的用户不存在!") return redirect(url_for("/index")) # convert to index page # posts = user.posts.all() # posts = user.posts.paginate(page, PER_PAGE, False).items pagination = Post.query.filter_by( user_id = current_user.id ).order_by( db.desc(Post.timestamp) ).paginate(page, USER_PER_PAGE, False) return render_template( "user.html", form=form, pagination=pagination)
def all(cls): return Returner.query.order_by(db.desc(Returner.id)).all()
def stories(user_id): return paginate(request, Story.query.order_by(db.desc("created")).filter_by(user_id=user_id), 50, "users/stories.html")
def clear_publishing_history(): """Method to unpublish all the existing tweets in the user DataBase""" query = db.session.query(TweetInfo).filter(TweetInfo.published == TWEET_PUBLISHED).order_by(db.desc(TweetInfo.id)) result = query.all() for tweet in result: tweet.published = TWEET_UNPUBLISHED db.session.commit()
def post(post_id): post = db.session.query(Post).filter(Post.id == post_id).first() html_txt = markdown.markdown(post.body_markdown, extensions=['fenced_code']) post.body = html_txt db.session.add(post) db.session.commit() tags = [] comments = [] # comment form form = CommentForm() # tag = db.session.query(Tag).join(PostTagRel).filter(PostTagRel.id == post_id).first().tag_name for tag_id in (db.session.query(PostTagRel).filter(PostTagRel.id == post_id).first().tag_id.split(',')): tag = db.session.query(Tag).filter(Tag.tag_id == tag_id).first().tag_name tags.append(tag) for com in (db.session.query(Comments).filter(Comments.post_id == post_id).order_by(db.desc(Comments.timestamp)).all()): comments.append(com) # form submit if form.validate_on_submit(): comment = Comments(content = form.comment.data, nickname = form.nickname.data, email = form.email.data, timestamp = time.strftime('Y%-M%-D% H%:M%', time.localtime(time.time())), post_id = post.id) db.session.add(comment) db.session.commit() flash('评论已发表') return redirect(url_for('post',post_id=post.id)) print form.errors return render_template('post.html', title = post.title, post = post, tags = tags, form = form, comments = comments)
def index(): tarefas_pendentes = Tarefa.query.filter(Tarefa.concluida==False).order_by(db.desc(Tarefa.id)).all() tarefas_concluidas = Tarefa.query.filter(Tarefa.concluida==True).order_by(db.desc(Tarefa.id)).all() return render_template('index.html', tarefas_pendentes=tarefas_pendentes, tarefas_concluidas=tarefas_concluidas)
def solution_list(): user = Account.query.filter_by(name = request.get_json().get("user")).first() problem_id = request.get_json().get("problem_id") ordering = request.get_json().get("ordering") solution_query = None if(problem_id == -1): if ordering == "CYL": solution_query = Solution.query.filter(Solution.userId == user.id, Problem.identifier == None).join(Problem, Problem.id == Solution.problemId).order_by(db.desc(Solution.cycles)) elif ordering == "NOD": solution_query = Solution.query.filter(Solution.userId == user.id, Problem.identifier == None).join(Problem, Problem.id == Solution.problemId).order_by(db.desc(Solution.nodeCount)) elif ordering == "INS": solution_query = Solution.query.filter(Solution.userId == user.id, Problem.identifier == None).join(Problem, Problem.id == Solution.problemId).order_by(db.desc(Solution.instructionCount)) else: if ordering == "CYL": solution_query = Solution.query.filter(Solution.userId == user.id , Solution.problemId == problem_id).order_by(db.desc(Solution.cycles)) elif ordering == "NOD": solution_query = Solution.query.filter(Solution.userId == user.id , Solution.problemId == problem_id).order_by(db.desc(Solution.nodeCount)) elif ordering == "INS": solution_query = Solution.query.filter(Solution.userId == user.id , Solution.problemId == problem_id).order_by(db.desc(Solution.instructionCount)) return jsonify({"results" : Solution.simpleJsonify(solution_query)})
def home(): stories = Story.query.order_by(db.desc("created")).limit(10) return render_template("pages/home.html", stories=stories)
def fetch_tweets(): """Method to fetch the tweets and update the counters""" query = db.session.query(TweetInfo).filter(TweetInfo.published == TWEET_UNPUBLISHED).order_by(db.desc(TweetInfo.id)) result = query.first() result.published = TWEET_PUBLISHED db.session.commit() return result
def solutionPage(): ordering = request.get_json().get("ordering") page = int(request.get_json().get("page")) -1 problem = Problem.query.filter_by(id = request.get_json().get("problemId")).first() if ordering == "CYL": return jsonify({"results" :Solution.simpleJsonify(Solution.query.filter_by(problemId = problem.id).order_by(db.desc(Solution.cycles)).offset(page*12).limit(12))}) elif ordering == "NOD": return jsonify({"results" :Solution.simpleJsonify(Solution.query.filter_by(problemId = problem.id).order_by(db.desc(Solution.nodeCount)).offset(page*12).limit(12))}) elif ordering == "INS": return jsonify({"results" :Solution.simpleJsonify(Solution.query.filter_by(problemId = problem.id).order_by(db.desc(Solution.instructionCount)).offset(page*12).limit(12))})
def comments(user_id): return paginate(request, Comment.query.order_by(db.desc("created")).filter_by(user_id=user_id), 50, "users/comments.html")