Ejemplo n.º 1
0
def player(pid):
    player = Player.query.get(pid)
    teams = db.session.query(Team.id).filter(
        db.or_(Team.player1_id == pid, Team.player2_id == pid)).subquery()

    all_teams = Team.query.filter(Team.id.in_(teams)).all()

    # team 1 is always the winning one
    won_matches = Match.query.filter(Match.team1_id.in_(teams)).all()
    lost_matches = Match.query.filter(Match.team2_id.in_(teams)).all()
    matches_played = len(won_matches) + len(lost_matches)

    made_crawl = Match.query.filter(Match.team1_id.in_(teams),
                                    Match.crawling).all()
    did_crawl = Match.query.filter(Match.team2_id.in_(teams),
                                   Match.crawling).all()

    points_sum = player.stat.points
    avg_points = float(points_sum - 1200) / float(matches_played)

    all_matches = Match.query.filter(
        db.or_(Match.team1_id.in_(teams), Match.team2_id.in_(teams))).join(
            MatchDay, Match.matchday).order_by(MatchDay.date).all()
    first_matchday = all_matches[0].matchday.date

    won_ids = [m.id for m in won_matches]
    lost_ids = [m.id for m in lost_matches]
    points_hist = []
    points = 1200
    matchdays = []
    lowest = (points, first_matchday)
    highest = (points, first_matchday)
    for m in all_matches:
        if m.id in won_ids:
            points += m.points
        elif m.id in lost_ids:
            points -= m.points
        else:
            raise RuntimeError('ERROR! you messed up!')
        points_hist.append(points)
        matchdays.append(m.matchday.date.isoformat())

        if points < lowest[0]:
            lowest = (points, m.matchday.date)
        if points > highest[0]:
            highest = (points, m.matchday.date)

    return render_template(
        'player.html',
        player=player,
        players=get_players_for_ranking(),
        teams=all_teams,
        avg_points=avg_points,
        matches_played=matches_played,
        made_crawl=made_crawl,
        did_crawl=did_crawl,
        first_matchday=first_matchday,
        lowest_points=lowest,
        highest_points=highest,
    )
Ejemplo n.º 2
0
 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()
Ejemplo n.º 3
0
def list(page_nr=1):
    items = News.query.filter(News.publish_date <= date.today(),
                              db.or_(News.archive_date >= date.today(),
                                     News.archive_date == None),  # noqa
                              db.or_(current_user.has_paid,
                                     db.not_(News.needs_paid))) \
        .order_by(desc(News.publish_date))

    can_write = role_service.user_has_role(current_user, Roles.NEWS_WRITE)
    return render_template('news/list.htm',
                           items=items.paginate(page_nr, 10, False),
                           archive=False, can_write=can_write)
Ejemplo n.º 4
0
 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)
Ejemplo n.º 5
0
def home():
    data = ['activities',
            'contact']

    revisions = get_revisions(data)
    news = News.query.filter(News.publish_date <= date.today(),
                             db.or_(News.archive_date >= date.today(),
                                    News.archive_date == None),  # noqa
                             db.or_(current_user.has_paid,
                                    db.not_(News.needs_paid)))\
                     .order_by(desc(News.publish_date)).limit(8).all()

    return render_template('home/home.htm', revisions=revisions,
                           title='Homepage', news=news)
Ejemplo n.º 6
0
def load_channel():
    all_messages = db.session.query(Message, User, Friends).join(
        User,
        db.or_(Message.sender == User.id, Message.receiver == User.id)).filter(
            db.or_(
                Message.receiver == current_user.id,
                Message.sender == current_user.id)).filter(
                    User.id != current_user.id).order_by(
                        db.desc(Message.timestamp)).group_by(User.id).join(
                            Friends,
                            db.and_(
                                Message.sender == Friends.user_id,
                                Message.receiver == Friends.friend_id)).filter(
                                    Friends.is_channel_on == True).all()
    return jsonify(messages=[useful(m) for m in all_messages])
Ejemplo n.º 7
0
def sign_up():
    form = SignUpForm()
    user = User()
    if form.validate_on_submit():
        user_name = request.form.get('user_name')
        user_email = request.form.get('user_email')

        register_check = User.query.filter(
            db.or_(User.nickname == user_name,
                   User.email == user_email)).first()
        if register_check:
            flash("error: The user's name or email already exists!")
            return redirect('/sign-up')

        if len(user_name) and len(user_email):
            user.nickname = user_name
            user.email = user_email
            user.role = ROLE_USER
            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash("The Database error!")
                return redirect('/sign-up')

            flash("Sign up successful!")
            return redirect('/index')

    return render_template("sign_up.html", title='Sign Up', form=form)
Ejemplo n.º 8
0
def atualizar_base(produtos):
    """
        recebe um lista dos produtos do site e
        atualiza a base do sistema
    """
    print(produtos)
    for p in produtos:
        sku = p['sku']
        break
        
        if sku.isdigit():
            sku = int(sku)
        
        produto = CissProdutoGrade.query.filter(
            CissProdutoGrade.idsubproduto == sku,
            db.or_(
                CissProdutoGrade.idtipo != 2,
                CissProdutoGrade.idtipo != 3
            )
        ).first()

        if produto:
            produto.idmodelo = 4
            produto.idtipo = 2
            produto.update()
        
        '''    
Ejemplo n.º 9
0
	def get(self, ticket_id=None):
		if(not ticket_id):
			args = get_parser.parse_args()
			if(not args.find):
				ticket = Ticket.query.filter(Ticket.state_id.notin_([4,5])).all() if(not args.page) else Ticket.query.paginate(args.page, 18, False).items
			else:
				query = []
				filtro = json.loads(args.find)
				if('descripcion' in filtro):
					query.append(Ticket.titulo.like('%{}%'.format(filtro['descripcion'])))
				if('estado' in filtro):
					query.append(Ticket.state_id == filtro['estado'])
				if('prioridad' in filtro):
					query.append(Ticket.priority_id == filtro['prioridad'])
				if('departamento' in filtro):
					query.append(Ticket.department_id == filtro['departamento'])
				if('fecha_desde' in filtro):
					query.append(Ticket.creado>='{}-{}-{}'.format(filtro['fecha_desde']['year'],filtro['fecha_desde']['month'],filtro['fecha_desde']['day']))
				if('fecha_hasta' in filtro):
					query.append(Ticket.creado>='{}-{}-{}'.format(filtro['fecha_hasta']['year'],filtro['fecha_hasta']['month'],filtro['fecha_hasta']['day']))
				if(len(query)>1):
					ticket = Ticket.query.filter(db.or_(*query)).all() if(not args.page) else Ticket.query.filter(db.or_(*query)).paginate(args.page, 18, False).items
				else:
					ticket = Ticket.query.filter(*query).all() if(not args.page) else Ticket.query.filter(*query).paginate(args.page, 18, False).items
		else:
			ticket = Ticket.query.filter_by(id=ticket_id).first()
			if(not ticket):
				abort(404, message="Ticket {} doesn't exist".format(ticket_id))
		return ticket, 200
Ejemplo n.º 10
0
 def search_book(term):
     return db.session.query(Books).filter(
         db.or_(Books.tags.any(Tags.name.ilike("%" + term + "%")),
                Books.series.any(Series.name.ilike("%" + term + "%")),
                Books.authors.any(Authors.name.ilike("%" + term + "%")),
                Books.publishers.any(Publishers.name.ilike("%" + term + "%")),
                Books.title.ilike("%" + term + "%"))).all()
Ejemplo n.º 11
0
def index():
    search_word = request.args.get('search', None)
    search_form = SearchForm()
    page = request.args.get('page', 1, type=int)

    the_alcohols = Alcohol.query
    if not current_user.can(Permission.UPDATE_ALCOHOL_INFORMATION):
        the_alcohols = Alcohol.query.filter_by(hidden=0)

    if search_word:
        search_word = search_word.strip()
        the_alcohols = the_alcohols.filter(
            db.or_(Alcohol.title.ilike(u"%%%s%%" % search_word),
                   Alcohol.manufacturer.ilike(u"%%%s%%" % search_word),
                   Alcohol.isbn.ilike(u"%%%s%%" % search_word),
                   Alcohol.tags.any(Tag.name.ilike(u"%%%s%%" % search_word)),
                   Alcohol.subtitle.ilike(
                       u"%%%s%%" % search_word))).outerjoin(Log).group_by(
                           Alcohol.id).order_by(db.func.count(Log.id).desc())
        search_form.search.data = search_word
    else:
        the_alcohols = Alcohol.query.order_by(Alcohol.id.desc())

    pagination = the_alcohols.paginate(page, per_page=8)
    result_alcohols = pagination.items
    return render_template("alcohol.html",
                           alcohols=result_alcohols,
                           pagination=pagination,
                           search_form=search_form,
                           title=u"List of alcohols")
Ejemplo n.º 12
0
    def leave_channel(self, user, message_id, channel_id):
        channel = models.Channel.query \
            .outerjoin(models.Channel.invited) \
            .filter(db.or_(models.User.id == user.id, models.Channel.private == False)) \
            .filter(models.Channel.id == channel_id) \
            .first()
        if channel is None:
            self.ws.send(json.dumps({
                'id': message_id,
                'value': {
                    'success': False,
                }
            }))

        channel.users.remove(user)
        db.session.commit()

        self.ws.send(json.dumps({
            'id': message_id,
            'value': {
                'success': True,
            }
        }))

        self.broadcast(json.dumps({
            'server': 'leave',
            'channel': channel.shallow_json(),
            'user': user.shallow_json(),
        }))
Ejemplo n.º 13
0
	def login_check(cls,user_name):
		user = cls.query.filter(db.or_(User.nickname == user_name,User.email == user_name)).first()

		if not user:

			return None
		return user
Ejemplo n.º 14
0
 def authenticate(cls, user_id, password):
     user = cls.query.filter(
         db.or_(
             func.lower(cls.username) == func.lower(user_id),
             func.lower(cls.email) == func.lower(user_id))).first()
     if user is not None and check_password_hash(user.password, password):
         return user
Ejemplo n.º 15
0
def index():
    search_word = request.args.get('search', None)
    search_form = SearchForm()
    page = request.args.get('page', 1, type=int)

    the_items = Item.query
    if not current_user.can(Permission.UPDATE_ITEM_INFORMATION):
        the_items = Item.query.filter_by(hidden=0)

    if search_word:
        search_word = search_word.strip()
        the_items = the_items.filter(
            db.or_(Item.title.ilike(u"%%%s%%" % search_word),
                   Item.author.ilike(u"%%%s%%" % search_word),
                   Item.itemtype.ilike(u"%%%s%%" % search_word),
                   Item.platform.ilike(u"%%%s%%" % search_word)))
        search_form.search.data = search_word
    else:
        the_items = Item.query.order_by(Item.id.desc())

    pagination = the_items.paginate(page, per_page=8)
    result_items = pagination.items
    return render_template("item.html",
                           items=result_items,
                           pagination=pagination,
                           search_form=search_form,
                           title=u"Lista pozycji")
Ejemplo n.º 16
0
def is_allowed_domain(domainname, current_user_id, checkrole=True):
    """Build a query to populate domains with user and group acls considered."""
    uqry = db.session.query(User)\
             .filter(User.id == current_user_id)\
             .first()
    if uqry:
        if uqry.role_id == 1:
            LOGGING.debug('user is an admin %s', uqry.username)
            return True

    domidqry = db.session.query(Domain.id)\
                 .filter(Domain.name == domainname)\
                 .first()
    retval = True
    if domidqry:
        if checkrole:
            duqry = db.session.query(Domain.id) \
                      .join(DomainUser)\
                      .filter(DomainUser.user_id == current_user_id)\
                      .subquery('duqry')
        dgqry = query_acldomains_fromuser(current_user_id)
        dgqry = dgqry.subquery('dgqry')

        netqry = db.session.query(Domain.id)
        if checkrole:
            netqry = netqry.filter(
                db.or_(Domain.id.in_(dgqry), Domain.id.in_(duqry)))
        else:
            netqry = netqry.filter(Domain.id.in_(dgqry))
        netqry = netqry.filter(Domain.id == domidqry.id)\
                       .all()

        retval = bool(netqry)

    return retval
Ejemplo n.º 17
0
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))
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
def signup():
    form = SignUpForm()
    user = User()
    if form.validate_on_submit():
        useremail = request.form.get('UserEmail')
        username = request.form.get('UserName')
        password = request.form.get('PassWord')
        checkUser = User.query.filter(
            db.or_(User.username == username,
                   User.email == useremail)).first()
        if checkUser:
            flash(u'该账号或昵称已经存在', 'flash-message lime')
            redirect('/signup')
        user.email = useremail
        user.password = password
        user.username = username
        try:
            db.session.add(user)
            db.session.commit()
        except:
            flash(u'数据库异常', 'flash-message lime')
            return redirect('/signup')
        else:
            flash(u'注册成功', 'flash-message green')
            return redirect('/login')

    return render_template('signup.html', form=form)
Ejemplo n.º 20
0
def publications(page=1):
    per_page = 100

    search = request.args.get('q')
    mine = 'mine' in request.args.keys()

    if search:
        searchQuery = '%{0}%'.format(search)

        query = Publication.query.filter(
            db.or_(Publication.title.ilike(searchQuery),
                   Publication.authors.ilike(searchQuery)))
    else:
        query = Publication.query

    if mine and current_user.is_authenticated:
        query = query.filter(Publication.author_id == current_user.id)

    query = query.order_by(Publication.pub_year.desc())

    pubs = query.filter_by(published=True).paginate(page, per_page)

    data = {
        'publications': [pub.serialize() for pub in pubs.items],
        'page': page,
        'total_pages': math.ceil(pubs.total / per_page),
        'q': search
    }

    return render_vue(data, title='Publications', menu='publications')
Ejemplo n.º 21
0
def sign_up():

    form = SignUpForm()
    user = uUser()
    if form.validate_on_submit():
        user_name = request.form.get('name')
        user_password = request.form.get('password')
        register_check = uUser.query.filter(
            db.or_(uUser.nickname == user_name,
                   uUser.password == '123456')).first()
        if register_check:
            flash("error:The user's name or email already exists!")
            return redirect('/sign-up')
        if len(user_name) and len(user_password):
            user.nickname = user_name
            user.password = user_password
            user.role = ROLE_USER
            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash("The Database error!")
                return redirect('/sign-up')
            flash("Sign up successful!")
            return render_template('index.html', nickname=user_name)
    return render_template('sign_up.html', form=form)
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
def sign_up():
    form = SignUpForm()
    user = User()
    if form.validate_on_submit():
        user_name = request.form.get('user_name')
        user_password = request.form.get('user_password')
        user_email = request.form.get('user_email')

        register_check = User.query.filter(
            db.or_(User.username == user_name,
                   User.email == user_email)).first()
        if register_check:
            flash("Error: Username or Email already exists.")
            return redirect(url_for('sign_up'))

        if len(user_name) and len(user_email) and len(user_password):
            user.username = user_name
            user.password_hash = generate_password_hash(user_password,
                                                        method='pbkdf2:sha1',
                                                        salt_length=8)
            user.email = user_email
            user.role = ROLE_USER
            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash("Database error.")
                return redirect(url_for('sign_up'))

            flash("Sign up successful.")
            return redirect(url_for('index'))

    return render_template("sign_up.html", form=form)
Ejemplo n.º 24
0
def sign_up():
    form = SignUpForm()
    user = User()
    if form.validate_on_submit():
        user_name = request.form.get('user_name')
        user_email = request.form.get('user_email')
        password = md5(request.form.get('password', type=str))

        print "###############################"
        print type(password)
        print "###############################"

        register_check = User.query.filter(
            db.or_(User.nickname == user_name,
                   User.email == user_email)).first()
        if register_check:
            flash("error: The user's name or email alerady exists")
            return redirect('/sign-up')
        if len(user_name) and len(user_email):
            user.nickname = user_name
            user.email = user_email
            user.password = password
            user.role = ROLE_USER
            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash('The DB error')
                return redirect('/sign-up')
    flash('the user registed success')
    return render_template('sign_up.html', form=form)
Ejemplo n.º 25
0
def sign_up():
    form = SignUpForm()
    user = User()
    if form.validate_on_submit():
        user_name = request.form.get('user_name')
        user_email = request.form.get('user_email')

        register_check = User.query.filter(db.or_(
            User.nickname == user_name, User.email == user_email)).first()
        if register_check:
            flash("error: The user's name or email already exists!")
            return redirect('/sign-up')

        if len(user_name) and len(user_email):
            user.nickname = user_name
            user.email = user_email
            user.role = ROLE_USER
            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash("The Database error!")
                return redirect('/sign-up')

            flash("Sign up successful!")
            return redirect('/index')

    return render_template(
        "sign_up.html",
        form=form)
Ejemplo n.º 26
0
def index():
    search_word = request.args.get('search', None)
    search_form = SearchForm()
    page = request.args.get('page', 1, type=int)

    the_books = Book.query
    if not current_user.can(Permission.UPDATE_BOOK_INFORMATION):
        the_books = Book.query.filter_by(hidden=0)

    if search_word:
        search_word = search_word.strip()
        the_books = the_books.filter(
            db.or_(Book.title.ilike(u"%%%s%%" % search_word),
                   Book.author.ilike(u"%%%s%%" % search_word),
                   Book.isbn.ilike(u"%%%s%%" % search_word),
                   Book.tags.any(Tag.name.ilike(u"%%%s%%" % search_word)),
                   Book.subtitle.ilike(
                       u"%%%s%%" % search_word))).outerjoin(Log).group_by(
                           Book.id).order_by(db.func.count(Log.id).desc())
        search_form.search.data = search_word
    else:
        the_books = Book.query.order_by(Book.id.desc())

    pagination = the_books.paginate(page, per_page=8)
    result_books = pagination.items
    return render_template("book.html",
                           books=result_books,
                           pagination=pagination,
                           search_form=search_form,
                           title=u"书籍清单")
Ejemplo n.º 27
0
def sign_up():
    form = SignUpForm()
    user = User()
    if form.validate_on_submit():
        user_name = request.form.get('user_name')
        user_email = request.form.get('user_email')
        password = request.form.get('password')
        password = generate_password_hash(password)
        register_check = User.query.filter(
            db.or_(User.nickname == user_name,
                   User.email == user_email)).first()
        if register_check:
            flash("用户名或邮箱重复")
            return redirect('/sign-up')

        if len(user_name) and len(user_email):
            user.nickname = user_name
            user.email = user_email
            user.role = ROLE_USER
            user.password = password
            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash("数据库读取错误,请重试")
                return redirect('/sign-up')

            flash("注册成功")
            return redirect('/login')

    return render_template("sign_up.html", form=form)
Ejemplo n.º 28
0
def index():
    # range of category numbers
    ids = db.session.query(Category).all()
    cat_range = [i.id for i in ids]
    # add three random id from each category:
    triple_meal = []
    for i in range(min(cat_range), max(cat_range) + 1):
        meal = db.session.query(Meal). \
            filter(Meal.category_id == i).all()
        for_shuffle = []
        for m in meal:
            for_shuffle += [m.id]
        key = shuffle(for_shuffle)
        random_meal = db.session.query(Meal). \
            filter(db.or_(Meal.id == key[0],
                          Meal.id == key[1],
                          Meal.id == key[2])).all()
        triple_meal += [random_meal]

    # variables to enable and disable some fields of page:
    mode = 'd-none'
    greeting = 'hidden'
    if session.get("user_id"):
        try:
            user_id = session.get('user_id')
            user = db.session.query(User).filter(
                User.id == user_id).first().mail
            if session.get('cart'):
                item_in_cart = session['cart']
                col_in_cart = []
                for i in item_in_cart:
                    col_in_cart += \
                        [db.session.query(Meal).
                             filter(Meal.title == i).first()]
            else:
                item_in_cart = []
                col_in_cart = []

            return render_template('main.html',
                                   category=category,
                                   triple_meal=triple_meal,
                                   mode_logon=mode,
                                   user=user,
                                   item_in_cart=item_in_cart,
                                   col_in_cart=col_in_cart)
        except AttributeError:
            return render_template('main.html',
                                   category=category,
                                   triple_meal=triple_meal,
                                   mode_logoff=mode,
                                   greeting=greeting,
                                   hidden_cart=greeting)

    return render_template('main.html',
                           category=category,
                           triple_meal=triple_meal,
                           mode_logoff=mode,
                           greeting=greeting,
                           hidden_cart=greeting)
Ejemplo n.º 29
0
def ready():
    if user_role() < 1:
        return redirect(url_for('profile'))
    vuses = []
    if user_role() == USER_STATES['ROLE_ADMIN']:
        admin_vuses = Admins_vuses.query.filter_by(user_id=current_user.id)
        vus_ids = [x.vus_id for x in admin_vuses if x.is_write]
        vuses = VUS.query.filter(db.or_(VUS.id == v for v in vus_ids))\
        .filter(VUS.is_active==True)
        users = db.session.query(User).filter_by(role = 0, approved = True)\
        .filter(db.or_(User.vus_id == v for v in vus_ids)).order_by(desc(User.entrance_year))\
        .order_by(User.vus_id)
    else:
        vuses = VUS.query.filter_by(is_active=True)
        users = db.session.query(User).filter_by(role = 0, approved = True)\
        .order_by(desc(User.entrance_year)).order_by(User.vus_id)

    documents = Document.query.all()

    userInfo = []
    for user in users:
        vusString = ''
        for vus in vuses:
            if vus.id == user.vus_id:
                vusString = vus.to_string()
                break

        userInfo.append({
            'id': user.id,
            'lastName': user.students_info.basic_information.last_name,
            'firstName': user.students_info.basic_information.first_name,
            'middleName': user.students_info.basic_information.middle_name,
            'year': user.login[-4:],
            'vus': vusString
        })

    docs = []
    for document in documents:
        docs.append({'id': document.id, 'name': document.name})

    return render_template('ready.html',
                           title=u'Готовые',
                           tab_active=1,
                           users=userInfo,
                           docs=docs,
                           vuses=vuses)
Ejemplo n.º 30
0
def perform_some_search(queryset, user_input):
    return queryset.filter(
        db.or_(
            models.Processed.title.like('%'+user_input+'%'),
            models.Processed.user.like('%'+user_input+'%'),
            models.Processed.platform.like('%'+user_input+'%')
            )
        )
Ejemplo n.º 31
0
 def login_check(cls, username, password):
     user = cls.query.filter(
         db.or_(User.email == username, User.username == username)).first()
     if not user:
         return None
     if user.password != password:
         return None
     return user
Ejemplo n.º 32
0
    def authenticate(cls, nickname, password):
        user = User.query.filter(db.or_(User.nickname == nickname)).first()

        if user:
            authenticated = user.check_password(password)
        else:
            authenticated = False
        return user, authenticated
Ejemplo n.º 33
0
    def login_check(cls, user_name):
        user = cls.query.filter(db.or_(
            User.nickname == user_name, User.email == user_name)).first()

        if not user:
            return None

        return user
Ejemplo n.º 34
0
def logbook():
    sel_country = request.args.get("country")
    sel_airport = request.args.get("airport")
    sel_date = request.args.get("date")

    sel_device_id = request.args.get("device_id")

    countries = get_countries_in_logbook()

    if sel_country:
        airports = get_airports_in_country(sel_country)
    else:
        airports = []

    if sel_airport:
        sel_airport = int(sel_airport)
        if sel_airport not in [airport["id"] for airport in airports]:
            sel_airport = None
            sel_date = None
        dates = get_dates_for_airport(sel_airport)
    else:
        dates = []

    if sel_date:
        sel_date = datetime.datetime.strptime(sel_date, "%Y-%m-%d").date()
        if sel_date not in [entry["date"] for entry in dates]:
            sel_date = dates[0]["date"]
    elif len(dates) > 0:
        sel_date = dates[0]["date"]

    # Get Logbook
    filters = []
    if sel_airport:
        filters.append(
            db.or_(Logbook.takeoff_airport_id == sel_airport,
                   Logbook.landing_airport_id == sel_airport))

    if sel_date:
        filters.append(db.func.date(Logbook.reftime) == sel_date)

    if sel_device_id:
        filters.append(Logbook.device_id == sel_device_id)

    if len(filters) > 0:
        logbook = db.session.query(Logbook).filter(*filters).order_by(
            Logbook.reftime)
    else:
        logbook = None

    return render_template("logbook.html",
                           title="Logbook",
                           sel_country=sel_country,
                           countries=countries,
                           sel_airport=sel_airport,
                           airports=airports,
                           sel_date=sel_date,
                           dates=dates,
                           logbook=logbook)
Ejemplo n.º 35
0
def logbooks():
    sel_country = request.args.get("country")
    sel_airport_id = request.args.get("airport_id")
    sel_date = request.args.get("date")

    sel_sender_id = request.args.get("sender_id")

    countries = get_used_countries()

    if sel_country:
        airports = get_used_airports_by_country(sel_country)
    else:
        airports = []

    if sel_airport_id:
        sel_airport_id = int(sel_airport_id)
        if sel_airport_id not in [airport.id for airport in airports]:
            sel_airport_id = None
            sel_date = None
        dates = get_dates_for_airport(sel_airport_id)
    else:
        dates = []

    if sel_date:
        sel_date = datetime.strptime(sel_date, "%Y-%m-%d").date()
        if sel_date not in [entry["date"] for entry in dates]:
            sel_date = dates[0]["date"]
    elif len(dates) > 0:
        sel_date = dates[0]["date"]

    # Get Logbook
    filters = []
    if sel_airport_id:
        filters.append(
            db.or_(Logbook.takeoff_airport_id == sel_airport_id,
                   Logbook.landing_airport_id == sel_airport_id))

    if sel_date:
        filters.append(db.func.date(Logbook.reference_timestamp) == sel_date)

    if sel_sender_id:
        filters.append(Logbook.sender_id == sel_sender_id)

    if len(filters) > 0:
        logbooks = db.session.query(Logbook).filter(*filters).order_by(
            Logbook.reference_timestamp).limit(100)
    else:
        logbooks = None

    return render_template("logbooks.html",
                           title="Logbook",
                           sel_country=sel_country,
                           countries=countries,
                           sel_airport_id=sel_airport_id,
                           airports=airports,
                           sel_date=sel_date,
                           dates=dates,
                           logbooks=logbooks)
Ejemplo n.º 36
0
def manage_publications(page=1):
    """View a list of publications with publish, edit, delete actions"""

    # Process delete request
    if request.method == 'POST':
        action = request.form.get('action')
        publication_id = request.form.get('id')
        if publication_id:
            publication = Publication.query.get(publication_id)
            ensureEditable(publication)

            if action == 'delete':
                db.session.delete(publication)
                db.session.commit()
            elif action == 'publish':
                publication.published = True
                db.session.commit()
            elif action == 'unpublish':
                publication.published = False
                db.session.commit()
        return redirect(request.full_path)

    per_page = 50
    offset = (page - 1) * per_page

    pub_year = request.args.get('pub_year')
    search = request.args.get('q')

    query = Publication.query

    if search:
        searchQuery = '%{0}%'.format(search)

        query = query.filter(
            db.or_(Publication.title.ilike(searchQuery),
                   Publication.authors.ilike(searchQuery)))
    if (pub_year):
        query = query.filter_by(pub_year=pub_year)
    publications = query.order_by(Publication.pub_year.desc()).paginate(
        page, per_page)
    data = {
        'publications': [
            pub.serialize() for pub in publications.items
            if current_user.canEdit(pub)
        ],
        'page':
        page,
        'total_pages':
        math.ceil(publications.total / per_page),
        'years': [
            y[0] for y in db.session.query(Publication.pub_year).order_by(
                Publication.pub_year.desc()).distinct().all()
        ],
        'q':
        search
    }
    return render_vue(data, title="Manage Publications", menu="publications")
Ejemplo n.º 37
0
    def search(self, keyword):
        criteria = []

        for keyword in keywords_split(keyword):
            keyword = u'%{0}%'.format(keyword)
            criteria.append(db.or_(Article.title.ilike(keyword), ))

        q = reduce(db.or_, criteria)
        return self.public().filter(q)
Ejemplo n.º 38
0
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))
Ejemplo n.º 39
0
 def get_all_channel_list(self, user, message_id):
     channels = models.Channel.query \
         .outerjoin(models.Channel.invited) \
         .filter(db.or_(models.User.id == user.id, models.Channel.private == False)) \
         .all()
     self.ws.send(json.dumps({
         'id': message_id,
         'value': [c.shallow_json() for c in channels],
     }))
Ejemplo n.º 40
0
def rss(locale='en'):
    name = 'via nieuws' if locale == 'nl' else 'via news'
    feed = AtomFeed(name, feed_url=request.url, url=request.url_root)
    items = News.query.filter(News.publish_date <= date.today(),
                              db.or_(News.archive_date >= date.today(),
                                     News.archive_date == None),  # noqa
                              db.or_(db.not_(News.needs_paid))) \
        .order_by(News.publish_date.desc()).limit(20)

    for item in items:
        published = datetime.combine(item.publish_date, datetime.min.time())
        title, content = item.get_localized_title_content(locale)
        feed.add(title, content, id=item.id, content_type='markdown',
                 published=published, updated=published,
                 url=url_for('news.view', news_id=item.id),
                 author=item.user.name)

    return feed.get_response()
Ejemplo n.º 41
0
    def authenticate(self, login, password):        
        user = self.filter(db.or_(User.username==login,
                                  User.email==login)).first()

        if user:
            authenticated = user.check_password(password)
        else:
            authenticated = False

        return user, authenticated
Ejemplo n.º 42
0
 def search(self, keywords):
     criteria = []
     for keyword in keywords.split():
         keyword = '%' + keyword + '%'
         criteria.append(db.or_(Post.title.ilike(keyword),
                                Post.description.ilike(keyword),
                                Post.link.ilike(keyword),
                                Post.tags.ilike(keyword),
                                User.username.ilike(keyword)))
     q = reduce(db.and_, criteria)
     return self.filter(q).join(User).distinct()
Ejemplo n.º 43
0
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)
Ejemplo n.º 44
0
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)
Ejemplo n.º 45
0
def sign_up():
    form = SignUpForm()

    if form.validate_on_submit():
        nickname = request.form.get("nickname")
        email = request.form.get("email")
        pw = request.form.get("password")
        re_pw = request.form.get("re_password")

        name_email_check = User.query.filter(db.or_(User.nickname == nickname, User.email == email)).first()
        if name_email_check:
            flash("错误: 用户名或者邮件地址已经存在!")
            return redirect(url_for("sign_up"))

        pw_check = (pw != re_pw)

        if pw_check:
            flash("两次输入的密码不相同!")
            return redirect(url_for("sign_up"))

        import helperlib
        if len(nickname) and len(email):
            user = User()
            user.nickname = nickname
            user.email = email
            user.password = helperlib.make_pw_hash(nickname, pw)
            user.role = ROLE_USER

            try:
                db.session.add(user)
                db.session.commit()
            except:
                flash("数据库错误!")
                return redirect(url_for("sign_up"))

            msg = Message("欢迎您来到行博", sender="*****@*****.**", recipients=[email])
            msg.body = """欢迎您来到行博。
                    我是行博CEO 行云。
                    您注册的账户名称是:{0}
                    祝您开心健康每一天!""".format(nickname)
            import helperlib
            helperlib.send_mail_async(mail, msg)

            flash("注册成功!注册邮件稍后发送至您的邮箱。")
            logout_user()
            return redirect(url_for("login"))
    return render_template(
        "sign_up.html",
        form = form)
Ejemplo n.º 46
0
    def authenticate(cls,login,password):
        """A classmethod for authenticating users
        It returns true if the user exists and has entered a correct password
        :param login: This can be either a username or a email address.
        :param password: The password that is connected to username and email.
        """

        user = cls.query.filter(db.or_(User.username == login,
                                       User.email == login)).first()

        if user and user.confirmed:
            authenticated = user.check_password(password)
        else:
            authenticated = False
        return user, authenticated, user.confirmed if user else False
Ejemplo n.º 47
0
def search():
    # print('main.search - 1')
    keywords = ('%s' % request.args.get('keywords', '')).strip()
    session['keywords'] = ('%s' % keywords)
    # print('main.search - keywords = %s' % keywords)
    if keywords is not None and '' != keywords:
        # print('main.search - 2')
        keywords = '%' + ('%s' % keywords).strip() + '%'
        # print('main.search - keywords = %s' % keywords)
        try:
            articleList = models.Article.query.filter(db.or_(
                models.Article.tag_list.like(keywords), models.Article.title.like(keywords))).all()
            return render_template('default/page_search_result.html',
                                   strs=strings(),
                                   keywords=session.get('keywords', ''), articleList=articleList)
        except Exception, e:
            logger.fatal("main.search - keywords=%s, err=%s" % (keywords, e))
Ejemplo n.º 48
0
    def search(lookup):
        try:
            result = (
                db.session.query(Subject)
                .filter(
                    db.or_(
                        Subject.subject_name.like("%" + str(lookup) + "%"),
                        Subject.subject_code.like("%" + str(lookup) + "%"),
                    )
                )
                .all()
            )
            return result

        except SQLAlchemyError as e:
            print(e)
            db.session.rollback()
            return {"msg": e, "code": 500}
Ejemplo n.º 49
0
def nominate():
    if not can_nominate():
        return redirect(url_for('elections.main'))

    nominated_ids = [n.nominee.id for n in current_user.nominations.all()]

    nominees = Nominee.query\
        .filter(db.or_(Nominee.valid == True, Nominee.valid == None))\
        .filter(db.not_(Nominee.id.in_(nominated_ids)))\
        .order_by(Nominee.name).all()  # noqa

    return render_template('elections/nominate.htm',
                           title='Docent van het jaar IW/Nomineren',
                           nominations=current_user.nominations,
                           data={'nominees': nominees,
                                 'nominate_url': url_for('elections.'
                                                         'submit_nomination'),
                                 'remove_url': url_for('elections.'
                                                       'remove_nomination')})
Ejemplo n.º 50
0
def edit(newsletter_id=None):
    form = NewsletterForm(request.form)

    if newsletter_id:
        newsletter = Newsletter.query.get_or_404(newsletter_id)
    else:
        newsletter = Newsletter()

    if request.method == 'GET':
        form.activities.data = [a.activity for a in newsletter.activities]
        form.news_items.data = [n.news_item for n in newsletter.news_items]

    if request.method == 'POST' and form.validate_on_submit():
        newsletter.activities.clear()
        newsletter.news_items.clear()

        for a in form.activities.data:
            newsletter.activities.append(NewsletterActivity(a))

        for n in form.news_items.data:
            newsletter.news_items.append(NewsletterNewsItem(n))

        db.session.add(newsletter)
        db.session.commit()

        flash(_('Newsletter saved'), 'success')
        return redirect(url_for('.all'))

    start_date = datetime.date.today().replace(day=1)
    prev_month = (start_date - datetime.timedelta(days=1)).replace(day=1)

    if not newsletter_id:
        selected_news_items = News.query.filter(
            News.created > prev_month, db.or_(
                News.archive_date >= datetime.date.today(),
                News.archive_date == None))\
            .order_by(News.created).all()  # noqa
    else:
        selected_news_items = []

    return render_template('newsletter/edit.htm', newsletter=newsletter,
                           form=form, selected_news_items=selected_news_items)
Ejemplo n.º 51
0
    def get_search_query(query: Optional[BaseQuery] = None, search_term: Optional[str] = None) -> BaseQuery:
        """
            Get a query that searches the users for the given search term on their names or emails

            The search term may contain wildcards (`*`).

            :param query: A base query object. If not given, the `User.query` will be used.
            :param search_term: The term for which the users will be searched. If `None`, a non-filtering query will be
                                returned.
            :return: The query object.
        """
        if query is None:
            query = User.query

        if search_term is None or search_term == '':
            return query

        # Replace the wildcard character with the SQL wildcard.
        search_term = search_term.replace('*', '%')
        return query.filter(db.or_(User.name.like(search_term), User._email.like(search_term)))
Ejemplo n.º 52
0
    def nominate(self, user):
        if not user.has_paid:
            raise Exception('Je moet betaald lid zijn om een docent te '
                            'nomineren')

        nominee_ids = [n.nominee_id for n in user.nominations.all()]
        nomination_n = Nominee.query.filter(Nominee.id.in_(nominee_ids))\
            .filter(db.or_(Nominee.valid == None, Nominee.valid == 1))\
            .count()  # noqa
        if nomination_n >= Nomination.MAX_PER_USER:
            raise Exception('Je mag maar %d docenten per persoon nomineren' %
                            (Nomination.MAX_PER_USER))

        if user.nominations.filter(Nomination.nominee_id == self.id).first():
            raise Exception('Je mag een docent maar een keer nomineren.')

        nomination = Nomination(self, user)
        db.session.add(nomination)
        db.session.commit()

        return nomination
Ejemplo n.º 53
0
    def get_channel(self, user, message_id, channel_name):
        """
        Channel that is either public or the user has been invited.
        """
        channel = models.Channel.query \
            .outerjoin(models.Channel.invited) \
            .filter(db.or_(models.User.id == user.id, models.Channel.private == False)) \
            .filter(models.Channel.name == channel_name) \
            .first()

        if channel is not None:
            # Load last 30 messages
            messages = list(channel.messages.limit(30))

            channel_json = channel.shallow_json()
            channel_json['messages'] = [m.shallow_json() for m in reversed(messages)]
            channel_json['users'] = [u.shallow_json() for u in channel.users]

            self.ws.send(json.dumps({
                'id': message_id,
                'value': channel_json,
            }))
Ejemplo n.º 54
0
def index():
    search_word = request.args.get('search', None)
    search_form = SearchForm()
    page = request.args.get('page', 1, type=int)

    the_books = Book.query
    if not current_user.can(Permission.UPDATE_BOOK_INFORMATION):
        the_books = Book.query.filter_by(hidden=0)

    if search_word:
        search_word = search_word.strip()
        the_books = the_books.filter(db.or_(
            Book.title.ilike(u"%%%s%%" % search_word), Book.author.ilike(u"%%%s%%" % search_word), Book.isbn.ilike(
                u"%%%s%%" % search_word), Book.tags.any(Tag.name.ilike(u"%%%s%%" % search_word)), Book.subtitle.ilike(
                u"%%%s%%" % search_word))).outerjoin(Log).group_by(Book.id).order_by(db.func.count(Log.id).desc())
        search_form.search.data = search_word
    else:
        the_books = Book.query.order_by(Book.id.desc())

    pagination = the_books.paginate(page, per_page=8)
    result_books = pagination.items
    return render_template("book.html", books=result_books, pagination=pagination, search_form=search_form,
                           title=u"书籍清单")
Ejemplo n.º 55
0
    def send_message(self, user, message_id, content, channel_id):
        # Fetch channel in question
        # Validates if user has permission to submit message to channel
        channel = models.Channel.query \
            .outerjoin(models.Channel.invited) \
            .filter(db.or_(models.User.id == user.id, models.Channel.private == False)) \
            .filter(models.Channel.id == channel_id) \
            .first()

        if channel is None:
            self.ws.send(json.dumps({
                'id': message_id,
                'value': {
                    'denied': True,
                }
            }))
        else:
            message = models.Message(channel_id=channel.id, user_id=user.id, content=content)
            db.session.add(message)
            db.session.commit()

            # Confirm message for specific user (releases their input field)
            self.ws.send(json.dumps({
                'id': message_id,
                'value': message.id,
            }))

            # Broadcast message to everyone
            # This is a dumb idea. All users in all channels (even private) get their
            # messages send to everyone, publicly. I would probably re-init the ws
            # using a query param or path, specifying my channel (e.g., client.ws.path).
            self.broadcast(json.dumps({
                'server': 'message',
                'channel': channel.shallow_json(),
                'message': message.shallow_json(),
                'user': user.shallow_json()
            }))
Ejemplo n.º 56
0
    def authenticate(cls, login, password):
        user = cls.query.filter(db.or_(User.email == login, User.username == login)).first()
        authenticated = user.check_password(password) if user else False

        return user, authenticated
Ejemplo n.º 57
0
 def get_user(cls,campID):
     "通过campID查询用户"
     user = cls.query.filter(db.or_(User.campID==campID)).first()
     if not user:
         return None
     return user
Ejemplo n.º 58
0
	def login_check(cls,user_name):
		#对user_name进行检查,如果user_name等于nickname或者email,则查询正确,返回第一个结果
		user=cls.query.filter(db.or_(User.nickname==user_name,User.email==user_name)).first()
		if not user:
			return None
		return user
Ejemplo n.º 59
0
 def get_users(cls):
     return cls.query.filter(db.or_(cls.status == 'pass', cls.status == 'banned'))
Ejemplo n.º 60
0
def news_factory():
    now = datetime.date.today()

    return News.query.filter(db.or_(News.archive_date >= now,
                                    News.archive_date == None))\
                     .order_by(News.created).all()  # noqa