Exemple #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')
Exemple #2
0
def login():
    print(type(request.get_data(as_text=True)))
    data = json.loads(request.get_data(as_text=True))
    # data = slp(request.get_data(as_text=True))
    name = data["name"]
    pwd = data["pwd"]
    try:
        user = User.query.filter_by(name=name).first_or_404()
        if user == None:
            return jsonify({
                "status": RET.NODATA,
                "message": error_map[RET.NODATA]
            })
    except:
        return jsonify({
            "status": RET.NODATA,
            "message": error_map[RET.NODATA]
        })
    if user.pwd != pwd:
        return jsonify({
            "status": RET.PWDERR,
            "message": error_map[RET.PWDERR]
        })
    uid = str(uuid.uuid4().hex)
    now_time = datetime.datetime.now()
    rd.set(uid, (now_time +
                 datetime.timedelta(days=+1)).strftime("%Y-%m-%d %H:%M:%S"))
    return jsonify({
        "userid": user.id,
        "message": error_map[RET.OK],
        "status": RET.OK,
        "token": uid
    })
Exemple #3
0
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
Exemple #4
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
Exemple #5
0
def regist():
    data = json.loads(request.get_data(as_text=True))
    # data = slp(request.get_data(as_text=True))
    name = data["name"]
    pwd = data["pwd"]
    token = str(uuid.uuid4().hex)
    now_time = datetime.datetime.now()
    rd.set(token, (now_time +
                   datetime.timedelta(days=+1)).strftime("%Y-%m-%d %H:%M:%S"))
    try:
        duser = User.query.filter_by(name=name).first_or_404()
        print("-----------------")
        if duser != None:
            return jsonify({
                "status": RET.DATAEXIST,
                "message": error_map[RET.DATAEXIST]
            })
        uid = str(uuid.uuid4().hex)
        user = User(
            name=name,
            pwd=pwd,
            info='',
            face=default_face,
            uuid=uid,
        )
        print("--------------")
        db.session.add(user)
        db.session.commit()
        uu = User.query.filter_by(name=name).first_or_404()
        return jsonify({
            "status": RET.OK,
            "message": error_map[RET.OK],
            "token": token,
            "userid": uu.id
        })
    except:
        uid = str(uuid.uuid4().hex)
        user = User(name=name, pwd=pwd, info='', face=default_face, uuid=uid)
        print("--------------")
        db.session.add(user)
        db.session.commit()
        uu = User.query.filter_by(name=name).first_or_404()
        return jsonify({
            "status": RET.OK,
            "message": error_map[RET.OK],
            "token": token,
            "userid": uu.id
        })
    def add_to_cache(self, value, label=None):
        if type(value) != str:
            value = ujson.dumps(value)
        key = self._get_key(label=label)
        resp = rd.set(name=key, value=value)
        rd.expire(name=key, time=app.config['CACHE_KEY_EXPIRE'])

        return resp
Exemple #7
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
Exemple #8
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('参数有误')
Exemple #9
0
def cache_user_json(user_json):
    """ Cache user_json to redis """
    key = Keys.user_json.format(user_json['id'])
    data = json.dumps(user_json, ensure_ascii=False)
    rd.set(key, data, ex=Keys.user_json_expire)
Exemple #10
0
def cache_status_json(status_json):
    """ Cache unprocessed status_json to redis """
    key = KEYS.status_json.format(status_json['id'])
    data = json.dumps(status_json, ensure_ascii=False)
    rd.set(key, data, ex=KEYS.status_json_expire)
Exemple #11
0
def cache_article_json(article_json):
    """ Cache article_json to redis """
    key = Keys.article_json.format(article_json['id'])
    data = json.dumps(article_json, ensure_ascii=False)
    rd.set(key, data, ex=Keys.article_json_expire)
Exemple #12
0
def cache_account_json(account_json) -> None:
    """ Cache unprocessed account_json to redis """
    key = KEYS.official_account_json.format(account_json['id'])
    data = json.dumps(account_json)
    rd.set(key, data, ex=KEYS.official_account_json_expire)
Exemple #13
0
def cache_group_json(group_json):
    """ Cache group_json to redis """
    key = KEYS.group_json.format(group_json['id'])
    data = json.dumps(group_json, ensure_ascii=False)
    rd.set(key, data, ex=KEYS.group_json_expire)