def update_max_altitudes_orm(): """Add max altitudes in logbook when flight is complete (takeoff and landing).""" current_app.logger.info("Update logbook max altitude.") logbook_entries = (db.session.query(Logbook.id, Sender.name).filter( db.and_(Logbook.takeoff_timestamp != db.null(), Logbook.landing_timestamp != db.null(), Logbook.max_altitude == db.null())).filter( Logbook.sender_id == Sender.id).limit(1).subquery()) max_altitudes = (db.session.query( logbook_entries.c.id, db.func.max(SenderPosition.altitude).label("max_altitude")).filter( db.and_( db.between_( SenderPosition.timestamp >= Logbook.takeoff_timestamp, SenderPosition.timestamp <= Logbook.landing_timestamp), SenderPosition.name == logbook_entries.c.name)).group_by( Logbook.id).subquery()) update_logbooks = db.session.query(Logbook).filter( Logbook.id == max_altitudes.c.id).update( {Logbook.max_altitude: max_altitudes.c.max_altitude}, synchronize_session="fetch") db.session.commit() finish_message = "Logbook (altitude): {} entries updated.".format( update_logbooks) return finish_message
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 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 leave_game(self, game_id, sid, player_id): player = db.session.query(model.Player).filter( db.and_(model.Player.sid == sid, model.Player.game_id == game_id)).first() if player is None: raise errors.UknownPlayer() # Player wants to leave if player.id == player_id: db.session.query(model.Player).filter( db.and_(model.Player.sid == sid, model.Player.game_id == game_id)).delete() db.session.query( model.Game).filter(model.Game.host_id == player.id).delete() # Player wants to kick elif db.session.query(model.Game).filter( db.and_(model.Game.host_id == player.id, model.Game.id == game_id)).first() is not None: db.session.query(model.Player).filter( db.and_(model.Player.id == player_id, model.Player.game_id == game_id)).delete() else: raise errors.ForbiddenAction() game = db.session.query( model.Game).filter(model.Game.id == game_id).first() if game is not None and game.stage != model.GameStage.pending: self.reset_game(game)
def stations2_filtered_pl(start, end): last_10_minutes = datetime.utcnow() - timedelta(minutes=10) query = (db.session.query( Receiver.name.label("s"), db.label( "lt", db.func.round(db.func.ST_Y(Receiver.location_wkt) * 10000) / 10000), db.label( "lg", db.func.round(db.func.ST_X(Receiver.location_wkt) * 10000) / 10000), db.case([(Receiver.lastseen > last_10_minutes, "U")], else_="D").label("u"), Receiver.lastseen.label("ut"), db.label("v", Receiver.version + "." + Receiver.platform), ).order_by(Receiver.lastseen).filter( db.or_(db.and_(start < Receiver.firstseen, end > Receiver.firstseen), db.and_(start < Receiver.lastseen, end > Receiver.lastseen)))) res = db.session.execute(query) stations = json.dumps({"stations": [dict(r) for r in res]}, default=alchemyencoder) return stations
def getCustomKeywords(taskId): rowData = Task.query.filter_by(id=taskId).first() caseIds = json.loads(rowData.case_id) projectData = Tree.query.filter_by(id=caseIds[0]).first() projectId = projectData.project_id keywordRootId = projectData.pid keywordRows = Tree.query.filter( db.and_(Tree.project_id == projectId, Tree.type == 4)).all() keywordRootConfig = CaseProjectSetting.query.filter_by( pid=keywordRootId).first() keywordRootlibs = [] if keywordRootConfig: keywordRootLibDatas = CaseLibs.query.filter( db.and_(CaseLibs.id.in_(json.loads( keywordRootConfig.libs)))).all() for lib in keywordRootLibDatas: keywordRootlibs.append(lib.name) keywordDatas = [] for keyword in keywordRows: keywordId = keyword.id keyInfo = CaseInfo.query.filter_by(pid=keywordId).first() caseSteps = [] caseStepDatas = CaseStep.query.filter_by(case_id=keywordId).order_by( db.asc(CaseStep.indexId)).all() for caseStep in caseStepDatas: caseSteps.append({'values': json.loads(caseStep.values)}) keywordDatas.append({ 'name': keyInfo.name, 'Arguments': json.loads(keyInfo.params), 'returns': json.loads(keyInfo.return_values), 'caseSteps': caseSteps, }) return keywordDatas, keywordRootlibs
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 get_userinfo(): sessionKey = request.values.get("sessionKey") username = sessionKey2Username.get(sessionKey) with db.Session() as session: members = session.query(Member).filter( db.and_(Member.username == username)).all() # todo 定义新的两个model histories = session.query(MemberUseLog).filter( db.and_(MemberUserLog.username == username)).all() favorites = session.query(MemberStar).filter( db.and_(MemberStar.username == username)).all() if len(members) == 0: return jsonify(dict(statusCode="400")) else: member = members[0] return jsonify( dict(statusCode="200", nickName=member.nickname, portrait=member.portrait, sex=member.sex, history='\t'.join( list(map(lambda history: history.fil_id, histories))), favority='\t'.join( list(map(lambda favorite: favorite.fil_id, favorites)))))
def index(): today_beginning = datetime.combine(date.today(), time()) senders_today = db.session.query(db.func.count( Sender.id)).filter(Sender.lastseen >= today_beginning).one()[0] receivers_today = db.session.query(db.func.count( Receiver.id)).filter(Receiver.lastseen >= today_beginning).one()[0] takeoffs_today = db.session.query(db.func.count(TakeoffLanding.id)).filter( db.and_(TakeoffLanding.timestamp >= today_beginning, TakeoffLanding.is_takeoff == db.true())).one()[0] landings_today = db.session.query(db.func.count(TakeoffLanding.id)).filter( db.and_(TakeoffLanding.timestamp >= today_beginning, TakeoffLanding.is_takeoff == db.false())).one()[0] sender_positions_today = db.session.query( db.func.sum(ReceiverStatistic.messages_count)).filter( ReceiverStatistic.date == date.today()).one()[0] sender_positions_total = db.session.query( db.func.sum(ReceiverStatistic.messages_count)).one()[0] last_logbook_entries = db.session.query(Logbook).order_by( Logbook.reference_timestamp.desc()).limit(10) return render_template("index.html", senders_today=senders_today, receivers_today=receivers_today, takeoffs_today=takeoffs_today, landings_today=landings_today, sender_positions_today=sender_positions_today, sender_positions_total=sender_positions_total, logbook=last_logbook_entries)
def test_registration(self): """ Test that a user can create a corpus and that this corpus has its data well recorded """ # Click register menu link self.driver.find_element_by_id("new_corpus_link").click() self.driver.implicitly_wait(15) # Fill in registration form self.driver.find_element_by_id("corpusName").send_keys( PLAINTEXT_CORPORA["Wauchier"]["name"]) self.writeMultiline(self.driver.find_element_by_id("tokens"), PLAINTEXT_CORPORA["Wauchier"]["data"]) self.driver.find_element_by_id("label_checkbox_create").click() self.driver.find_element_by_id("submit").click() self.driver.implicitly_wait(15) self.assertIn(url_for('main.corpus_get', corpus_id=1), self.driver.current_url, "Result page is the corpus new page") self.assertEqual( db.session.query(Corpus).filter( Corpus.name == PLAINTEXT_CORPORA["Wauchier"]["name"]).count(), 1, "There should be one well named corpus") corpus = db.session.query(Corpus).filter( Corpus.name == PLAINTEXT_CORPORA["Wauchier"]["name"]).first() self.assertEqual(corpus.delimiter_token, None, "We did not set a delimiter token") tokens = db.session.query(WordToken).filter( WordToken.corpus == corpus.id) self.assertEqual(tokens.count(), 25, "There should be 25 tokens") saint = db.session.query(WordToken).filter( db.and_(WordToken.corpus == 1, WordToken.lemma == "saint")) self.assertEqual(saint.count(), 1, "There should be the saint lemma") saint = saint.first() self.assertEqual(saint.form, "seint", "It should be correctly saved") self.assertEqual(saint.label_uniform, "saint", "It should be correctly saved and unidecoded") self.assertEqual(saint.POS, "ADJqua", "It should be correctly saved with POS") self.assertEqual(saint.morph, None, "It should be correctly saved with morph") oir = db.session.query(WordToken).filter( db.and_(WordToken.corpus == 1, WordToken.lemma == "öir")) self.assertEqual(oir.count(), 1, "There should be the oir lemma") oir = oir.first() self.assertEqual(oir.form, "oïr", "It should be correctly saved") self.assertEqual(oir.label_uniform, "oir", "It should be correctly saved and unidecoded") self.assertEqual(oir.POS, "VERinf", "It should be correctly saved with POS") self.assertEqual(oir.morph, None, "It should be correctly saved with morph")
def university_dep(id): degrees=degree.query.all() univer = university.query.get_or_404(id) university_department = department.query.filter(db.and_(department.university_id == id,department.degree == degree.id)).all() text = request.args.get('text') search = "%{}%".format(text) if request.args.get('degree'): university_department = department.query.filter(db.and_(department.university_id == id,department.degree ==request.args.get('degree'), department.name.like(search))).all() return render_template('university.html',dep=university_department, univer = univer,degree=degrees)
def join_to_room(ws_message): channel = Friends.query.filter( db.or_( db.and_(Friends.user_id == current_user.id, Friends.friend_id == int(ws_message["friend_id"])), db.and_(Friends.user_id == int(ws_message["friend_id"]), Friends.friend_id == current_user.id))).order_by( Friends.id).first() join_room(str(channel.id))
def orders(): orderByUser = cart.query.filter( cart.user_id == session['user']['id']).all() user_order = Orders(user_id=session['user']['id']) db.session.add(user_order) db.session.commit() ord = Orders.query.all() for newOrder in orderByUser: amounts = newOrder.qty * newOrder.priceItem delete = cart.query.filter( cart.user_id == session['user']['id']).first() db.session.delete(delete) for i in ord: k = orderItems(product=newOrder.product_id, qty=newOrder.qty, price=newOrder.priceItem, amount=amounts, order_id=i.id) db.session.add(k) db.session.commit() mail_user = users.query.filter(users.id == session['user']['id']).all() with mail.connect() as conn: for us in mail_user: order_id = orderItems.query.filter( Orders.id == orderItems.order_id).order_by( Orders.id.desc()).first() orderByus = Orders.query.filter( db.and_(Orders.id == orderItems.order_id, Orders.user_id == session['user']['id'])).all() prodName = Product.query.filter( Product.id == orderItems.product).first() for byUs in orderByus: orderItemsByUser = orderItems.query.filter( db.and_(Orders.id == orderItems.order_id, Orders.user_id == session['user']['id'])).all() for itemsByuser in orderItemsByUser: message = 'This is your purchase' + '<br>' + 'name: ' + str(byUs.id) + '<br>' \ 'qty:' + str( itemsByuser.qty) + '<br>' \ 'price:' + str(itemsByuser.price) + '$' + '<br>' \ 'Amount:' + str( itemsByuser.amount) + '$' + '<br>' subject = "Your Purchase %s" % us.username msg = Message(recipients=[us.email], html=message, subject=subject) conn.send(msg) return redirect(url_for('shopping_cart'))
def return_message(friend_id): all_messages = Message.query.filter( db.or_( db.and_(Message.sender == int(friend_id), Message.receiver == current_user.id), db.and_(Message.sender == current_user.id, Message.receiver == int(friend_id)))).order_by( db.desc(Message.timestamp)).all() return jsonify(messages=[m.serialize() for m in all_messages])
def new_fights(self, status=None): q = Fight.query.filter( db.or_( db.and_(Fight.user1_id == self.id, Fight.user1_score == 0), db.and_(Fight.user2_id == self.id, Fight.user2_score == 0) ) ) if status: q = q.filter(Fight.status == status) return q
def is_host(self, game_id, sid): player_id = db.session.query(model.Player.id).filter( db.and_(model.Player.sid == sid, model.Player.game_id == game_id)).first() if player_id is None: raise errors.UknownPlayer() elif db.session.query(model.Game).filter( db.and_(model.Game.host_id == player_id[0], model.Game.id == game_id)).first() is None: return False return True
def dialogue_with(self, whom): """ 双方都删除也会保留对话内容 :param whom:对话人物 :return: """ return Message.query.filter( db.or_(db.and_(Message.sender == self, Message.receiver == whom), db.and_(Message.sender == whom, Message.receiver == self)), Message.message_type == MessageType.standard)
def search_all(keyword, page, per_page): Article = app.article.models.Article Book = app.book.models.Book query = u"%{0}%".format(keyword) publishs = db.session.query(UserPublish, Article, Book).outerjoin(Article, ( db.and_(UserPublish.source=="article", UserPublish.publish_id==Article.id))).\ outerjoin(Book, (db.and_(UserPublish.source=="book", UserPublish.publish_id == Book.id))).filter( db.or_(Article.access=="public", Book.access=="public")).filter(db.or_( Article.title.ilike(query), Book.name.ilike(query))).order_by( UserPublish.timestamp.desc()) return paginate(publishs, page, per_page=per_page, error_out=False)
def get_last_message(self): return User.query.with_entities( User.nickname, func.max(Message.id).label("max_id"), ).filter( db.or_( db.and_(User.id == Message.receiver_id, Message.sender_id == self.current_user_id), db.and_( User.id == Message.sender_id, Message.receiver_id == self.current_user_id))).group_by( User.nickname).subquery("sub_in_chat")
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 newest_publishs(num): Article = app.article.models.Article Book = app.book.models.Book publishs = db.session.query(UserPublish, Article, Book).outerjoin(Article, ( db.and_(UserPublish.source=="article", UserPublish.publish_id==Article.id))).\ outerjoin(Book, (db.and_(UserPublish.source=="book", UserPublish.publish_id == Book.id))).filter( db.or_( db.and_(Article.access=="public", Article.is_necessary==0), db.and_(Book.access=="public", Book.is_necessary==0) )).group_by(UserPublish.id).order_by( UserPublish.timestamp.desc()).limit(num).all() return publishs
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 page(page, per_page): last_catalog = Book.create_subquery("last_catalog") catalogs = db.session.query(Book, BookCatalog) \ .outerjoin(last_catalog, last_catalog.c.id == Book.id) \ .outerjoin(BookCatalog, db.and_( BookCatalog.book_id == Book.id, BookCatalog.publish_order == last_catalog.c.order)) \ .options( db.Load(Book).undefer("brief"), db.Load(BookCatalog).undefer("abstract")) \ .filter(db.and_( Book.access == 1, last_catalog.c.order.isnot(None))) \ .order_by(BookCatalog.first_publish.desc()) return paginate(catalogs, page, per_page=per_page, error_out=False)
def last_message_property(self, friend): last_message = Message.query.filter( db.or_( db.and_(Message.sender == self.id, Message.receiver == friend.id), db.and_(Message.sender == friend.id, Message.receiver == self.id))).order_by( db.desc(Message.timestamp)).first() if (last_message is None) or (last_message.sender == friend.id) or (last_message.status == 0): return True else: return False
def reply(id): """ 回复评论里面的评论 :param id: :return: """ reply = Reply.query.get_or_404(id) # 当前回复 comment = reply.comment user = reply.author # 我要回复的人 replies = comment.replies.filter( db.or_(db.and_(Reply.author == current_user, Reply.user == user), db.and_(Reply.author == user, Reply.user == current_user))).all() form = CommentForm() if comment.topic_type == 'post': return execute_reply(comment, form=form, user=user, topic_type='post', replies=replies) elif comment.topic_type == 'question': return execute_reply(comment, form=form, user=user, topic_type='question', replies=replies) elif comment.topic_type == 'answer': return execute_reply(comment, form=form, user=user, topic_type='answer', replies=replies) elif comment.topic_type == 'favorite': return execute_reply(comment, form=form, user=user, topic_type='favorite', replies=replies) else: return execute_reply(comment=comment, form=form, user=user, topic_type='', replies=replies)
def get_translations_with_limit_and_offset(current_user): if not check_session(): return jsonify({'message': 'You are not logged in!', 'isLoggedIn': False}) limit = request.args.get('limit') offset = request.args.get('offset') sort_by = request.args.get('sortBy') collectionId = request.args.get('collectionId') sort_direction = request.args.get('sortDirection') if limit == None or offset == None or collectionId == None: return jsonify({'message': 'Invalid request. Limit, offset and collectionId arguments have to be instance of Ing', 'contentIsSent': False}) collection = Collection.query.with_entities(Collection.name, Collection.id, Collection.createdAt, Collection.updatedAt).filter(db.and_(Collection.id==collectionId,Collection.userId==current_user.id)).first() if not collection: return jsonify({'message': 'Collection is not found!', 'contentIsSent': False}) order_by_options = {"primaryPhrase": Translation.primaryPhrase, "secondaryPhrase": Translation.secondaryPhrase, "createdAt": TranslationStatus.createdAt, "updatedAt": TranslationStatus.updatedAt, "id": Translation.id,} order_by = order_by_options.get(sort_by) translations = db.session.query(Translation, TranslationStatus).outerjoin(TranslationStatus, Translation.id == TranslationStatus.translationId).filter(db.and_(TranslationStatus.collectionId==collection.id)).order_by(set_direction(sort_direction)(order_by)).limit(limit).offset(offset).all() translationsQuantity = db.session.query(TranslationStatus).filter(db.and_(TranslationStatus.collectionId==collection.id)).count() learnedQuantity = db.session.query(TranslationStatus).filter(db.and_(TranslationStatus.collectionId==collection.id, TranslationStatus.isLearned==True)).count() translations_response = [] for translation in translations: trans = {} trans['id'] = translation[0].id trans['primaryLanguage'] = translation[0].primaryLanguage trans['secondaryLanguage'] = translation[0].secondaryLanguage trans['primaryPhrase'] = translation[0].primaryPhrase trans['secondaryPhrase'] = translation[0].secondaryPhrase trans['isLearned'] = translation[1].isLearned trans['updatedAt'] = translation[1].updatedAt trans['collectionId'] = translation[1].collectionId translations_response.append(trans) return jsonify({'translations': translations_response, 'collectionData': {'learnedQuantity' : learnedQuantity, 'translationsQuantity': translationsQuantity, 'id': collection.id, 'name': collection.name, 'updatedAt': collection.updatedAt, 'createdAt': collection.createdAt}, 'isSent': True})
def tags(): search_tags = request.args.get('search', None) page = request.args.get('page', 1, type=int) the_tags = Tag.query.outerjoin(book_tag).group_by(book_tag.c.tag_id).order_by( db.func.count(book_tag.c.book_id).desc()).limit(30).all() search_form = SearchForm() search_form.search.data = search_tags data = None pagination = None if search_tags: tags_list = [s.strip() for s in search_tags.split(',') if len(s.strip()) > 0] if len(tags_list) > 0: the_books = Book.query if not current_user.can(Permission.UPDATE_BOOK_INFORMATION): the_books = Book.query.filter_by(hidden=0) the_books = the_books.filter( db.and_(*[Book.tags.any(Tag.name.ilike(word)) for word in tags_list])).outerjoin(Log).group_by( Book.id).order_by(db.func.count(Log.id).desc()) pagination = the_books.paginate(page, per_page=8) data = pagination.items return render_template('book_tag.html', tags=the_tags, title='Tags', search_form=search_form, books=data, pagination=pagination)
def get_line(self, start_time, end_time): """ get a slice of raw points of data :param start_time: :param end_time: :return: """ period = self.get_abstract().period start_time = utils.iceil(start_time, period) end_time = utils.iceil(end_time, period) data_raw = Raw.query.filter( db.and_(Raw.data_id.is_(self.get_id()), Raw.timestamp.between(start_time, end_time))) # data_raw = {point.timestamp: point for point in data_raw} line = [ Raw(timestamp=point.timestamp, value=point.value) for point in data_raw ] # line = [] # for timestamp in range(start_time, end_time, period): # if timestamp in data_raw: # line.append(data_raw[timestamp]) # else: # line.append(Raw(timestamp=timestamp)) return line
def archive(page_nr=1): items = News.query.filter(db.and_(News.archive_date < date.today(), News.archive_date != None)) # noqa return render_template('news/list.htm', items=items.paginate(page_nr, 10, False), archive=True)
def login_check(cls, user_name, password): user = cls.query.filter( db.and_(User.user_name == user_name, User.password == password) ).first() if not user: return None return user
def get_ref(self, start_time, end_time): """ get reference lines for data :param start_time: :param end_time: :return: """ period = self.get_abstract().period start_time = utils.iceil(start_time, period) end_time = utils.iceil(end_time, period) ref_names = db.session.query(db.distinct(Point.name)).all() lines = [] for ref_name, in ref_names: points = Point.query.filter( db.and_(Point.data_id.is_(self.get_id()), Point.name.is_(ref_name), Point.timestamp.between(start_time, end_time))) points = {point.timestamp: point for point in points} line = [] for timestamp in range(start_time, end_time, period): if timestamp in points: line.append((timestamp, points[timestamp].value, points[timestamp].range)) else: line.append((timestamp, None, None)) lines.append((ref_name, line)) return lines
def load_datalist(toadd): if toadd == 'round': return dict( selections=db.session.query(Selection.selection_name).all(), primers=db.session.query(Primers.name).filter( Primers.role.in_(('SELEX', 'PD'))).all(), rounds=db.session.query(Rounds.round_name).all(), targets=db.session.query(Selection.target).distinct().all()) elif toadd == 'selection': return dict( targets=db.session.query(Selection.target).distinct().all()) elif toadd == 'sequence_round': note = db.session.query(distinct(Sequence.note)).filter( db.and_(Sequence.note.isnot(None), Sequence.note != '')).all() n = Counter() for i in note: for j in i[0].split(','): if j.strip(): n[(j.strip(), )] += 1 return dict(known_sequence=db.session.query( KnownSequence.sequence_name).all(), common_note=[i[0] for i in n.most_common(10)]) else: return {}
def vote(self, user_id): """ allow a user to vote on a post. if we have voted already (and they are clicking again), this means that they are trying to unvote the post, return status of the vote for that user """ already_voted = self.has_voted(user_id) vote_status = None if not already_voted: # vote up the post db.engine.execute( post_upvotes.insert(), user_id=user_id, post_id=self.id ) if self.votes is None: self.votes = 1 self.votes += 1 vote_status = True else: # unvote the post db.engine.execute( post_upvotes.delete( db.and_( post_upvotes.c.user_id == user_id, post_upvotes.c.post_id == self.id ) ) ) self.votes -= 1 vote_status = False db.session.commit() # for the vote count return vote_status
def tags(): search_tags = request.args.get('search', None) page = request.args.get('page', 1, type=int) the_tags = Tag.query.outerjoin(alcohol_tag).group_by( alcohol_tag.c.tag_id).order_by( db.func.count(alcohol_tag.c.alcohol_id).desc()).limit(30).all() search_form = SearchForm() search_form.search.data = search_tags data = None pagination = None if search_tags: tags_list = [ s.strip() for s in search_tags.split(',') if len(s.strip()) > 0 ] if len(tags_list) > 0: the_alcohols = Alcohol.query if not current_user.can(Permission.UPDATE_ALCOHOL_INFORMATION): the_alcohols = Alcohol.query.filter_by(hidden=0) the_alcohols = the_alcohols.filter( db.and_(*[ Alcohol.tags.any(Tag.name.ilike(word)) for word in tags_list ])).outerjoin(Log).group_by(Alcohol.id).order_by( db.func.count(Log.id).desc()) pagination = the_alcohols.paginate(page, per_page=8) data = pagination.items return render_template('alcohol_tag.html', tags=the_tags, title='Tags', search_form=search_form, alcohols=data, pagination=pagination)
def counting_shows(): """ returns a number. counts all show = True from Puppy and is == current_capacity""" update_capacity = db.session.query(Shelter).all() for shel in update_capacity: shel.current_capacity = db.session.query(Puppy, Shelter).join(Shelter).filter(db.and_(Shelter.id == shel.id, Puppy.show==True)).count() db.session.add(shel) db.session.commit()
def counting_shows(): update_capacity = db.session.query(Shelter).all() for shel in update_capacity: shel.current_capacity = db.session.query(Puppy, Shelter).join(Shelter).filter(db.and_(Shelter.id == shel.id, Puppy.show==True)).count() db.session.add(shel) db.session.commit() print "Successful update"
def api_schedule(semester): """Build a per-session schedule using the `sections` URL parameter. It must be formatted similarly to `sections=CODE100.01,CODE110.04`, which would select the class CODE100 section 1 and CODE110 section 4.""" # Get the pairs of class codes and section numbers. section_pairs = [tuple(pair.split('.')) for pair in request.args.get('sections').split(',')] try: sections = Section.query.join(Semester) \ .filter(Semester.name == semester.upper()) \ .filter(db.tuple_(Section.class_code, Section.number)\ .in_(section_pairs)).all() except DBAPIError: app.logger.info("DB Backend does not support compound key 'IN' queries, \ reverting to composed 'OR/AND' query.") # Because the backend does not support in_ for tuples, we abuse *args # and list comprehensions to create a subsitute query. sections = Section.query.join(Semester) \ .filter(Semester.name == semester.upper()) \ .filter(db.or_( *tuple((db.and_( Section.class_code == code, Section.number == number) for code, number in section_pairs)))) \ .all() return sections
def api_section_events(semester, class_code, section_number): """List calendar events for a particular section of a class.""" section = Section.query.join(Semester) \ .filter(Semester.name == semester.upper()) \ .filter(db.and_(Section.class_code == class_code.upper(), Section.number == section_number)).one() return section.events()
def schedule_events(semester): """Build a per-session schedule just like the above endpoint, but also generate all events. Also can generate iCalendar format output.""" # Get the pairs of class codes and section numbers. section_pairs = [tuple(pair.split('.')) for pair in request.args.get('sections').split(',')] s = Semester.query.filter(Semester.name == semester.upper()).one() try: sections = Section.query.join(Semester) \ .filter(Semester.name == semester.upper()) \ .filter(db.tuple_(Section.class_code, Section.number)\ .in_(section_pairs)).all() except DBAPIError: app.logger.info("DB Backend does not support compound key 'IN' queries, \ reverting to composed 'OR/AND' query.") # Because the backend does not support in_ for tuples, we abuse *args # and list comprehensions to create a subsitute query. sections = Section.query.join(Semester) \ .filter(Semester.name == semester.upper()) \ .filter(db.or_( *tuple((db.and_( Section.class_code == code, Section.number == number) for code, number in section_pairs)))) \ .all() return itertools.chain( *(b.events() for b in s.breaks), *(section.events() for section in sections))
def int_for_range(start_id, emd_id): if end_id: return db.and_( column>=start_id, column<end_id ) else: return column>=start_id
def api_section(semester, class_code, section_number): section = ( Section.query.join(Semester) .filter(Semester.name == semester.upper()) .filter(db.and_(Section.class_code == class_code, Section.number == section_number)) .one() ) print(section) return section
def archive(page_nr=1): if not ModuleAPI.can_read('news'): return abort(403) items = News.query.filter(db.and_(News.archive_date < date.today(), News.archive_date != None)) # noqa return render_template('news/list.htm', items=items.paginate(page_nr, 10, False), archive=True)
def shelter_profile(shelter_id,shelter_name, page=1): SHELTERS = Shelter.query.all() PUPPY = Puppy.query.filter(Puppy.shelter_id==shelter_id).all() shelter_profile = Shelter.query.filter_by(id=shelter_id).one() puppy = Puppy.query.filter(db.and_(Puppy.shelter_id==shelter_id, Puppy.show==True)).paginate(page,4,False) return render_template('shelter_profile.html', shelter_id=shelter_id, shelter_name=shelter_name, shelter_profile=shelter_profile, puppy=puppy, SHELTERS=SHELTERS, PUPPY=PUPPY)
def has_voted(self, user_id): """ did the user vote already """ select_votes = post_upvotes.select( db.and_( post_upvotes.c.user_id == user_id, post_upvotes.c.post_id == self.id ) ) rs = db.engine.execute(select_votes) return False if rs.rowcount == 0 else True
def restricted(self, user): if user and user.is_moderator: return self q = self.join(Case) criteria = [Case.access==Case.PUBLIC] if user: criteria.append(Case.author_id==user.id) if user.friends: criteria.append(db.and_(Case.access==Case.FRIENDS, Case.author_id.in_(user.friends))) return q.filter(reduce(db.or_, criteria))
def list(page_nr=1): if not ModuleAPI.can_read('news'): return abort(403) items = News.query.filter( db.and_( db.or_( News.archive_date >= date.today(), News.archive_date == None), News.publish_date <= date.today()))\ .order_by(desc(News.publish_date)) # noqa return render_template('news/list.htm', items=items.paginate(page_nr, 10, False), archive=False)
def home(): data = ['activities', 'contact'] revisions = get_revisions(data) news = News.query.filter( db.and_( db.or_( News.archive_date >= date.today(), News.archive_date == None), News.publish_date <= date.today()))\ .order_by(desc(News.publish_date)).limit(8).all() # noqa return render_template('home/home.htm', revisions=revisions, title='Homepage', news=news)
def _getreview(grade="All"): """获取当前页内容""" page=request.args.get("page",type=int)#接收当前页。并非从param返回,是控件自动传递的 rp=request.args.get("rp",type=int) sortcol=request.args.get('sortname')#获取要排序的行 sorttype=request.args.get('sortorder')#获取排序方式 if grade=="All": _score_items=Score_items.query.filter(Score_items.status==2).all() else : #按照年级来返回需要审核的内容 _score_items=Score_items.query.filter(db.and_(Score_items.status==2,User.get_user_byID(Score_items.user_id).grade==grade)).all() _score_items_af=sorter(_score_items,sortcol,sorttype) return jsonify(pageslicer(page,rp,_score_items_af))
def restricted(self, user=None): """ Returns posts filtered for a) public posts b) posts authored by the user c) posts authored by friends """ if user and user.is_moderator and user.is_admin: return self criteria = [Post.access==Post.PUBLIC] if user: criteria.append(Post.author_id==user.id) if user.friends: criteria.append(db.and_(Post.access==Post.FRIENDS, Post.author_id.in_(user.friends))) return self.filter(reduce(db.or_, criteria))
def getUserScoreitems(self,campID,time_st,time_ed,start,end): """返回符合条件的全部加分条目 args: campID:一卡通号 time_st time_ed """ user=User.query.filter(User.campID==campID).first() if start==None or end==None: result=Score_items.query.filter(Score_items.user_id==user.id).all() else: #单纯求时间差,是可以用字符串的,但是如果要使用timedelta则必须要转换成datetime类型 # result=Score_items.query.filter(db.and_(time_st,time_ed.between(self.tm.dbTime(start),self.tm.dbTime(end)+timedelta(days=1)),Score_items.user_id==user.id)).all() result=Score_items.query.filter(db.and_(time_st.between(self.tm.dbTime(start),self.tm.dbTime(end)), time_ed.between(self.tm.dbTime(start),self.tm.dbTime(end)), Score_items.user_id==user.id)).all() return result
def reset_password(hash=0): """ Reset form existing of two fields, password and password_repeat. Checks if the hash in the url is found in the database and timestamp has not expired. """ form = ResetPassword(request.form) # Request the ticket to validate the timer ticket = PasswordTicket.query.filter( db.and_(PasswordTicket.hash == hash)).first() # Check if the request was followed within a hour if ticket is None or ((datetime.now() - ticket.created_on).seconds > 3600): flash(_('No valid ticket found')) return redirect(url_for('user.request_password')) if form.validate_on_submit(): user = User.query.filter(User.id == ticket.user).first() if not user: flash(_('There is something wrong with the reset link.'), 'danger') return redirect(url_for('user.request_password')) # Actually reset the password of the user user.password = bcrypt.hashpw(form.password.data, bcrypt.gensalt()) login_user(user) db.session.add(user) db.session.commit() flash(_('Your password has been updated.'), 'success') return redirect(url_for('user.view_single', user_id=user.id)) else: flash_form_errors(form) return render_template('user/reset_password.htm', form=form)
def test_follow_question(self): # Add two users u1 = User(email='*****@*****.**', password='******') u2 = User(email='*****@*****.**', password='******') db.session.add_all([u1, u2]) db.session.commit() # u1 add a question q = Question(user=u1, title='abc', content='abc') self.assertEqual(u1.questions_count(), 1) # u2 follow this question u2.follow_question(q) user_on_question = UserOnQuestion.query.filter(db.and_( UserOnQuestion.user == u2, UserOnQuestion.question == q) ).first() self.assertFalse(user_on_question is None) # u2 unfollow this question u2.unfollow_question(q) self.assertFalse(user_on_question.follow)
def get_confirm_user(cls,code): user=cls.query.filter(db.and_(User.reg_token==code,User.active==False)).first() return user
def get_data_by_rs_id(rs_id, category=None, label=None): """ Get data by rs_id :param rs_id: generated by Data Operator for mapping resources set :param category: specific category :param label: specific label in category :return: JSON """ try: # get user_id and resource_set_id by rs_id rs = ResourceSet.query.filter_by(rs_id=rs_id).first() if rs is None: raise NotFound(payload={'detail': ('Invalid parameter <rs_id>:{0}').format(rs_id)}) user_id = rs.user_id resource_set_id = rs.id # whether specific an categoriess if category is not None: # get the id of this category ca = Categories.query.filter_by(name=category).first() if ca is None: raise NotFound(payload={'detail': ('can not find {0} in source').format(category)}) # raise ValueError('Invalid parameter <category>') # whether resource has been registered u_ca = LinkRsData.query.filter(db.and_( LinkRsData.resource_set_id == resource_set_id, LinkRsData.categories_id == ca.id )).first() # if not, return None if u_ca is None: raise NotFound(payload={ 'detail': 'the category you request have not been registered in the resource set!' }) # if yes, return data # get all subsets of this category if label is not None: lb = Label.query.filter(db.and_( Label.c_id == ca.id, Label.name == label )).all() else: lb = Label.query.filter_by(c_id=ca.id).all() data = [] # get data for b in lb: cd = Data.query.filter(db.and_( Data.user_id == user_id, Data.label_id == b.id )).order_by(Data.timestamp).all() if b.u_id is None: temp_unit = None else: temp_unit = b.units.name data.append({ 'label': b.name, 'sample': [d.serialized for d in cd], 'units': temp_unit }) return { 'name': category, 'data': data } # if not specific categories # get all categories in this resource set ca = LinkRsData.query.filter_by(resource_set_id=resource_set_id).all() if ca is None: return None result = [] # get user's data in this resource set by user_id and categories_id for i in ca: # get all labels of resource set lb = Label.query.filter_by(c_id=i.categories_id).all() data = [] for b in lb: cd = Data.query.filter(db.and_( Data.user_id == user_id, Data.label_id == b.id )).order_by(Data.timestamp).all() if b.u_id is None: temp_unit = None else: temp_unit = b.units.name data.append({ 'label': b.name, 'sample': [d.serialized for d in cd], 'units': temp_unit }) result.append({ 'name': i.categories.name, 'data': data }) return result except NotFound as e: # app_log.error(repr(e), extra={'sender': 'DataSource'}) raise e except Exception as e: # app_log.error(repr(e), extra={'sender': 'DataSource'}) raise e
def list(): s = session_to_user(request, session) if s.auth_error: return auth_error_return_helper(s) try: page = int(request.args.get('page')) or 1 except Exception: page = 1 terms = request.args.get('term') or None orders = [] filter = [] filter_user = s.id if terms: for terms in csv.reader([terms], skipinitialspace=True, delimiter=' '): terms = terms for term in terms: subterm = term.split(':') subterm_len = len(subterm) # Filter by views if subterm[0] == 'views' and subterm_len == 2: if subterm[1][0] == '>': filter.append(Object.viewcount >= subterm[1][1:]) elif subterm[1][0] == '<': filter.append(Object.viewcount <= subterm[1][1:]) elif subterm[1][0] == '=': filter.append(Object.viewcount == subterm[1][1:]) # Order by elif subterm[0] == 'by' and subterm_len in (2, 3): if subterm_len == 3: orders.append([subterm[1], subterm[2]]) else: orders.append([subterm[1], 'default']) # Is ... elif subterm[0] == 'is' and subterm_len in (2, 3): # Is deleted if subterm[1] == 'deleted': if subterm_len == 3 and subterm[2] == 'no': filter.append(Object.deleted == False) # noqa else: filter.append(Object.deleted == True) # noqa # Is type ... if subterm[1] in ('link', 'file'): if subterm_len == 2: filter.append(Object.type == subterm[1]) # Special search features for admins elif s.role_admin and subterm[0] == 'user' and subterm_len == 2: filter_user = subterm[1] # No special rule, search text fields else: if not term.strip() == '': term = term.replace('%', '\\%') term = term.replace('*', '%') filter.append(db.or_(Object.oid.like(term), Object.title.like(format_object_title(term)), Object.link.like(term) )) data = Object.query orders.append(['date_created', 'default']) for order in orders: if order[0] == 'views': order[0] = 'viewcount' elif order[0] in ('id', 'object'): order[0] = 'oid' elif order[0] == 'date': order[0] = 'date_created' elif order[0] == 'created': order[0] = 'date_created' elif order[0] == 'modified': order[0] = 'date_modified' elif order[0] == 'lastviewed': order[0] = 'last_viewed' # Order by ... string to object if not order[0] in ('date_created', 'date_modified', 'last_viewed', 'title', 'link', 'oid', 'viewcount', 'size'): continue ordero = getattr(Object, order[0]) ordero = ordero.asc() if order[1] == 'asc' else ordero.desc() data = data.order_by(ordero) if not filter_user == '*': filter.append(Object.owner == filter_user) data = data.filter(db.and_(*filter)) data = data.paginate(page=page, per_page=15) return render_template('objects/list.html', s=s, data=data, term=request.args.get('term'))
def auth(cls,email,password): user = cls.query.filter(db.and_(User.email==email,User.password==password)).first() return user,user and user.active
def exist_user(cls,email): user = cls.query.filter(db.and_(User.email==email,User.active==True)).first() return bool(user)
def gen(): res = db.session.query(Event.stamp, Event.sensor_id, Event.message).filter(db.and_(Event.stamp>=start, Event.stamp<=end, Event.sensor_id.in_(sids), Event.message.in_(['ON', 'OFF']))).order_by(Event.stamp) for row in res.yield_per(5): a = '\t'.join([str(str(row.stamp)[:-6]),str(sense[row.sensor_id]), str(row.message), '\n']) yield a