예제 #1
0
def login():
    if request.method == 'POST':
        id = request.form['id']
        password = request.form['password']
        try:

            user = User.query.filter_by(id=id).first()  # 일치하는 id 쿼링
            check_pw = bcrypt.check_password_hash(user.password,
                                                  password)  # 패스워드 일치 여부 확인

            if user is not None and check_pw == True:  # 로그인 완료 시
                rd.set('id', id)  # redis server 에 세션(id 값, 로그온 사용자) 저장
                flash("로그인 하였습니다.")  # alert 메시지 전달
                return render_template('login/menu.html', id=rd.get('id'))
            else:
                flash("로그인 실패.")
                return render_template('login/login_fail.html')

        except:
            flash("로그인 실패.")
            return render_template('login/login_fail.html')

    if rd.get('id') is not None:  # 세션에 아이디(로그온)가 존재할 경우, 로그인 완료 페이지로 로딩.
        return render_template('login/menu.html', id=rd.get('id'))
    else:  # 세션에 아이디가 존재하지 않을 경우
        return render_template('login/login.html')
예제 #2
0
def get_status_json(id: IntLike,
                    only_from_cache=False,
                    process_json=True) -> Union[dict, None]:
    """Get processed status_json

    * None is returned in case of status is not found
    * `only_from_cache` is for multiget_status_json()
    """
    key = KEYS.status_json.format(id)
    data = rd.get(key)
    # data is a dict with bytes key and bytes value
    if data:  # hit in redis cache
        result = json.loads(data.decode())
        rd.expire(key, KEYS.status_json_expire)
        if process_json:
            return Status.process_json(result)
        return result
    if only_from_cache:
        return None
    print("Can't load status {} from redis".format(id))
    print("Try to load from mysql")
    status = Status.query.get(id)
    if status is None:
        print("Can't load status {} from mysql".format(id))
        return None
    result = status.to_json(cache=True)
    cache_status_json(result)
    if process_json:
        return Status.process_json(result)
    return result
예제 #3
0
파일: articles.py 프로젝트: wemecan/School
def get_article_json(id: IntLike,
                     only_from_cache=False,
                     process_json=True) -> Union[dict, None]:
    """
    Get  article json by id

    `only_from_cache` is for multiget_article_json()
    """
    key = Keys.article_json.format(id)
    data = rd.get(key)  # none is returned if not exists
    if data is not None:
        json_article = json.loads(data.decode())
        rd.expire(key, Keys.article_json_expire)
        if not process_json:
            return json_article
        return Article.process_json(json_article)
    if only_from_cache:
        return None
    article = Article.query.get(id)
    if article is None:
        return None
    json_article = article.to_json(cache=True)
    cache_article_json(json_article)
    if not process_json:
        return json_article
    return Article.process_json(json_article)
예제 #4
0
def check_t(token):
    key = token
    stri = rd.get(key)
    stri = str(stri)
    stri = stri[2:-2]
    try:
        limitime = datetime.datetime.strptime(stri, "%Y-%m-%d %H:%M:%S")
    except:
        return True
    if limitime < datetime.datetime.now():
        return True
    else:
        return False
예제 #5
0
파일: users.py 프로젝트: ping203/School
def get_user(id: IntLike):
    """ None is returned if user can't found """
    key = Keys.user.format(id)
    data = rd.get(key)
    if data != None:
        user = pickle.loads(data)
        user = db.session.merge(user, load=False)
        rd.expire(key, Keys.user_expire)
        return user
    user = User.query.get(id)
    if user != None:
        data = pickle.dumps(user)
        rd.set(key, data, Keys.user_expire)
    return user
예제 #6
0
 def verify_auth_token(token):
     import app.cache as Cache
     import app.cache.redis_keys as KEYS
     """ Get current User from token """
     token_key = KEYS.user_token.format(token)
     data = rd.get(token_key)
     if data is not None:
         return Cache.get_user(data.decode())
     s = Serializer('auth' + current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
         rd.set(token_key, data['id'], KEYS.user_token_expire)
         return Cache.get_user(data['id'])
     except:
         return None
예제 #7
0
def get_user_json(id: IntLike) -> Union[dict, None]:
    """
    None is returned in case of user not exists
    """
    key = Keys.user_json.format(id)
    data = rd.get(key)
    if data:
        json_user = json.loads(data.decode())
        rd.expire(key, Keys.user_json_expire)
        return User.process_json(json_user)
    user = get_user(id)
    if user is None:
        return None
    json_user = user.to_json(cache=True)
    cache_user_json(json_user)
    return User.process_json(json_user)
예제 #8
0
def get_official_account_json(id: IntLike):
    """ Get official_account_json from redis by id

    None is returned in case of not found
    """
    key = KEYS.official_account_json.format(id)
    data = rd.get(key)
    if data is not None:
        json_account = json.loads(data.decode())
        rd.expire(key, KEYS.official_account_json_expire)
        return OfficialAccount.process_json(json_account)
    account = OfficialAccount.query.get(id)
    if account is None:
        return None
    json_account = account.to_json(cache=True)
    cache_account_json(json_account)
    return OfficialAccount.process_json(json_account)
예제 #9
0
def get_group_josn(id: IntLike):
    """
    Get group json from redis
    None is returned in case of not found
    """
    key = KEYS.group_json.format(id)
    data = rd.get(key)
    if data is not None:
        json_group = json.loads(data.decode())
        rd.expire(key, KEYS.group_json_expire)
        return Group.process_json(json_group)
    group = Group.query.get(id)
    if group is None:
        return None
    json_group = group.to_json(cache=True)
    cache_group_json(json_group)
    return Group.process_json(json_group)
예제 #10
0
def get_group_user_title(group_id: IntLike, user_id: IntLike):
    """
    Get user's title in some group
    "" is returned if not found
    """
    key = KEYS.group_user_title.format(group_id=group_id, user_id=user_id)
    data = rd.get(key)
    if data is not None:
        rd.expire(key, KEYS.group_user_title_expire)
        return data.decode()
    sql = """
    select title from group_memberships
    where user_id=:UID and group_id=:GID
    """
    result = db.engine.execute(text(sql), UID=user_id, GID=group_id)
    res = result.first()
    if res is None:
        return ""
    title = res[0]
    rd.set(key, title, ex=KEYS.group_user_title_expire)
    return title
예제 #11
0
def get_status():
    """ 获取动态
    分类:
    1. 获取某条特定动态, 团体微博, 团体帖子
        params = { id }
    3. 获取个人微博(时间序)
        params = {
            type: user,
            user_id:
        }
    2. 获取团体微博(时间序)
        params = {
            type: group_status,
            group_id:
        }
    2. 获取用户动态(时间序)
        params = {
            type: status,
        }
    3. 获取团体帖子(热门序)
        params = {
            type: post,
            group_id = Integer
        }
    4. 获取推荐(热门序)
        params = {
            type: timeline,
        }
    5. 获取关注微博(时间序)
        params = {
            type: followed,
        }
    6. 获取话题下的微博:
        params = {
            type: topic,
            topic_name: //
        }
    公共参数
        limit: 可选, default=10
    Note:
    1. 根据offset排序的小问题:
        a. 当某条内容上升到offset之前, 用户可能错过, 忽略不计,
        b. 当某条内容下降到offset之后, 用户可能重新刷到, 客户端需要处理重叠
    2. 当返回空数组时, 代表没有更多内容, 客户端自行处理
    """
    id = request.args.get('id', -1, type=int)
    type = request.args.get('type', '')
    user_id = request.args.get('user_id', -1, type=int)
    group_id = request.args.get('group_id', -1, type=int)
    only_with_comment = request.args.get('only_with_comment', "")
    topic = request.args.get('topic', "")
    offset = request.args.get('offset', 0, type=int)
    limit = request.args.get('limit', 10, type=int)

    if id != -1:
        return jsonify(Cache.get_status_json(id))

    if type == 'user':
        u = Cache.get_user(user_id)
        if u is None:
            return not_found('找不到该用户')
        ss = Status.query.filter_by(user=u)
        ss = ss.order_by(Status.timestamp.desc())
        ss = ss.offset(offset).limit(limit)
        ss = [s.to_json() for s in ss]
        return jsonify(ss)

    if type == 'group_status':
        group = Group.query.get(group_id)
        if group is None:
            return not_found('找不到该团体')
        ss = Status.query.filter_by(group=group, type_id=Status.TYPES['GROUP_STATUS'])
        ss = ss.order_by(Status.timestamp.desc())
        ss = ss.offset(offset).limit(limit)
        ss = [s.to_json() for s in ss]
        return jsonify(ss)

    if type == "status":
        ss = Status.query.filter_by(type_id=Status.TYPES['USER_STATUS'])
        ss = ss.order_by(Status.id.desc())
        ss = ss.offset(offset).limit(limit)
        ss = [s.to_json() for s in ss]
        return jsonify(ss)

    if type == 'post':
        ss = Status.query.filter_by(type_id=Status.TYPES['GROUP_POST'])
        if group_id != -1:
            ss = ss.filter_by(group_id=group_id)
        ss = ss.order_by(Status.timestamp.desc())
        ss = ss.offset(offset).limit(limit)
        ss = [s.to_json() for s in ss]
        return jsonify(ss)

    if type == 'hot':
        ss = Status.query.order_by(Status.timestamp.desc())
        ss = ss.offset(offset).limit(limit)
        ss = [s.to_json() for s in ss]
        rank.get_fresh()
        return jsonify(ss)

    if type == 'timeline':
        ### TODO: with entities might be useful here
        if not hasattr(g, 'user'):
            return jsonify([])
        sql2 = """
        select * from (
            select 0 as kind, id, timestamp
            from statuses where user_id=:UID or user_id in (
                select followed_id from user_follows as F where F.follower_id=:UID
            )
            union
            select 1 as kind, id, timestamp
            from articles where official_account_id in (
                select official_account_id from subscriptions as S where S.users_id=:UID
            )
        ) as t order by timestamp DESC limit :LIMIT offset :OFFSET;
        """ # `S.users_id` because there is a typo in column name
        result = db.engine.execute(text(sql2), UID=g.user.id,
                LIMIT=limit, OFFSET=offset)
        result = list(result)
        status_ids = [ item['id'] for item in result
                if item['kind'] == 0]
        article_ids = [ item['id'] for item in result
                if item['kind'] == 1 ]
        statuses = Status.query.filter(Status.id.in_(
            status_ids)).all()
        articles = Article.query.filter(Article.id.in_(
            article_ids)).all()
        res = statuses + articles
        res = sorted(res, key=lambda x: x.timestamp, reverse=True)
        res = [item.to_json() for item in res]
        return jsonify(res)


    #if type == "trending":
        #ids = rank.get_mixed()[offset:offset+limit]
        #ss = [Status.query.get(id).to_json() for id in ids]
        #return jsonify(ss)


    if type == 'topic':
        key = Keys.topic_id.format(topic_name=topic)
        data = rd.get(key)
        if data != None:
            topic_id = data.decode()
        else:
            t = Topic.query.filter_by(topic=topic).first()
            if t is None:
                return jsonify([])
            topic_id = t.id
            rd.set(key, topic_id, Keys.topic_id_expire)
        sql = """
            select status_id from status_topic
            where topic_id=:TOPIC_ID
            order by status_id DESC limit :LIMIT offset :OFFSET;
        """
        result = db.engine.execute(text(sql), TOPIC_ID=topic_id,
                OFFSET=offset, LIMIT=limit)
        result = list(result)
        status_ids = [item['status_id'] for item in result]
        statuses = Cache.multiget_status_json(status_ids)
        res_map = {}
        for s in statuses:
            res_map[s['id']] = s
        res = [ res_map[id] for id in status_ids ]
        return jsonify(res)

    return bad_request('参数有误')
예제 #12
0
 def get_from_cache(self, label=None):
     str_value = rd.get(name=self._get_key(label=label))
     return ujson.loads(str_value) if str_value else str_value