Beispiel #1
0
def my_gifts():
    uid = getattr(g, REQUEST_USER_ID)
    gifts_of_mine = Gift.get_user_gifts(uid)
    isbns = [gift.isbn for gift in gifts_of_mine]
    wish_counts = Gift.get_wish_counts(isbns)
    view = MyGifts(gifts_of_mine, wish_counts)
    return SuccessResponse(data=view.gifts)()
Beispiel #2
0
def satisfy_wish(wid):
    """
    向他人赠送书籍
    :param wid: 心愿id
    :return:
    """
    uid = getattr(g, REQUEST_USER_ID)
    wish = Wish.query.get_or_404(wid)
    wisher = User.query.filter(User.id == wish.user_id,
                               User.is_deleted == False).first_or_404()
    gift = Gift.query.filter_by(user_id=uid, isbn=wish.isbn).first()
    if not gift:
        return ErrorResponse(SATISFY_WISH_ERROR).make()
    current_wish = Wish.query.filter_by(user_id=wisher.id,
                                        launched=False,
                                        isbn=wish.isbn).first()
    if not current_wish:
        return ErrorResponse(SATISFY_WISHER_ERROR).make()
    can = wisher.can_send_drift()
    if not can:
        return ErrorResponse(USER_CANNOT_DRIFT).make()
    gifter = User.query.filter(User.id == gift.user_id,
                               User.is_deleted == False).first()
    drift_url = config.FRONT_DRIFT_URL
    send_email(wisher.email,
               '有人想送你一本书',
               'email/satisify_wish.html',
               wisher=wisher,
               gifter=gifter,
               gift=gift,
               drift_url=drift_url,
               wish=wish)
    return SuccessResponse(data=SATISFY_WISH_MSG)()
Beispiel #3
0
def my_wish():
    uid = getattr(g, REQUEST_USER_ID)
    wishes_of_mine = Wish.get_user_wishes(uid)
    isbns = [wish.isbn for wish in wishes_of_mine]
    gift_counts = Wish.get_gift_counts(isbns)
    wishes = MyWishes(wishes_of_mine, gift_counts)
    return SuccessResponse(data=wishes.gifts)()
Beispiel #4
0
def pending():
    uid = getattr(g, REQUEST_USER_ID)
    drifts = Drift.query.filter(
        or_(Drift.requester_id == uid,
            Drift.gifter_id == uid)).order_by(desc(Drift.create_time)).all()
    data = DriftCollection(drifts, uid).data
    return SuccessResponse(data=data)()
Beispiel #5
0
def redraw_from_wish(isbn):
    uid = getattr(g, REQUEST_USER_ID)
    wish = Wish.query.filter_by(isbn=isbn, launched=False,
                                user_id=uid).first_or_404()
    with db.auto_commit():
        wish.is_deleted = True
    return SuccessResponse()()
Beispiel #6
0
def logout():
    uid = getattr(g, REQUEST_USER_ID, None)
    if uid:
        key = login_token_key.format(uid)
        redis.delete(key)
        return SuccessResponse(NotContent)()
    else:
        return ErrorResponse(NOT_LOGIN).make()
Beispiel #7
0
def personal_center():
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.filter_by(id=uid).first()
    if not user:
        return ErrorResponse(USER_NOT_EXIST).make()
    schema = UserPersonalSchema()
    data = schema.dump(user.summary).data
    return SuccessResponse(data=data)()
Beispiel #8
0
def register():
    args = request.get_json()
    schema = RegisterValSchema(strict=True).load(args)
    with db.auto_commit():
        user = User()
        user.set_attrs(schema.data)
        db.session.add(user)
    return SuccessResponse(CREATED)()
Beispiel #9
0
def send_drift():
    uid = getattr(g, REQUEST_USER_ID)
    schema = DriftValSchema(strict=True)
    data = schema.load(request.get_json()).data
    current_gift = Gift.query.get_or_404(data['gift_id'])
    user_from_gift = User.query.get_or_404(current_gift.user_id)
    current_user = User.query.get_or_404(uid)
    save_drift(data, current_gift, user_from_gift, current_user)
    # todo 提醒用户 email or sms
    return SuccessResponse()()
Beispiel #10
0
def forget_password_request():
    schema = ResetEmailValSchema(strict=True)
    email = schema.load(request.get_json()).data['email']
    user = User.query.filter_by(email=email).first()
    if not user:
        return ErrorResponse(USER_NOT_EXIST).make()
    token = generate_token(user.id, reset_password_token_key, config.RESET_TOKEN_EXPIRE_TIME)
    forget_url = config.FRONT_RESET_EMAIL_URL
    send_email(email, '重置你的密码', 'email/reset_password.html', user=user, token=token, forget_url=forget_url)
    return SuccessResponse(Accepted)()
Beispiel #11
0
def redraw_from_gifts(gid):
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.get_or_404(uid)
    gift = Gift.query.filter_by(id=gid, launched=False, user_id=uid).first_or_404()
    drift = Drift.query.filter_by(gift_id=gid, pending=PendingStatus.Waiting.value).first()
    if drift:
        return ErrorResponse(REDRAW_GIFT_ERROR).make()
    with db.auto_commit():
        user.beans -= Decimal(0.5).quantize(Decimal('0.00'))
        gift.is_deleted = True
    return SuccessResponse()()
Beispiel #12
0
def login():
    schema = LoginValSchema(strict=True).load(request.get_json())
    data = schema.data
    user = User.query.filter_by(email=data['email']).first()
    if not user:
        return ErrorResponse(USER_NOT_EXIST).make()
    if user.check_password(data['password']):
        token = generate_token(user.id, login_token_key, config.LOGIN_TOKEN_EXPIRE_TIME)
        data = {'token': token, 'nickname': user.nickname}
        return SuccessResponse(data=data)()
    else:
        return ErrorResponse(USER_PASSWORD_ERROR).make()
Beispiel #13
0
def forget_password(token):
    schema = ForgetPasswordValSchema(strict=True)
    password = schema.load(request.get_json()).data['password']
    payload = decode_token(token)
    # 验证token一致性
    redis_key = reset_password_token_key.format(payload['uid'])
    token_from_redis = redis.get(redis_key)
    if check_token(token, token_from_redis):
        User.reset_password(payload['uid'], password)
        redis.delete(redis_key)
        return SuccessResponse(NotContent)()
    else:
        return ErrorResponse(TOKEN_INVALID).make()
Beispiel #14
0
def drift(gid):
    uid = getattr(g, REQUEST_USER_ID)
    current_user = User.query.get_or_404(uid)
    current_gift = Gift.query.get_or_404(gid)
    if current_gift.is_yourself_gift(uid):
        # 不能自己给自己发起鱼漂
        return ErrorResponse(SEND_DRIFT_IS_YOURSELF).make()
    # 检验当前用户能否发起鱼漂请求
    can = current_user.can_send_drift(current_gift.isbn)
    if not can:
        return ErrorResponse(USER_CANNOT_DRIFT).make()
    user_from_gift = User.query.get_or_404(current_gift.user_id).summary
    user_from_gift.update({'user_beans': str(current_user.beans)})
    return SuccessResponse(data=user_from_gift)()
Beispiel #15
0
def before_request():
    logger.debug("request ip: %s, path: %s, args: %s, body: %s",
                 request.remote_addr, request.path, request.args,
                 request.data.decode('utf-8'))
    if request.method == 'OPTIONS':
        return SuccessResponse()()
    login_urls = set(
        [url.decode('utf-8') for url in redis.smembers(login_url_key)])
    try:
        if request.endpoint.split('.')[-1] in login_urls:
            return check_request_token()
    except AttributeError as err:
        logger.error(err)
        return ErrorResponse(ENDPOINT_NOT_EXIST).make()
Beispiel #16
0
def change_password():
    uid = getattr(g, REQUEST_USER_ID, None)
    if uid:
        schema = ChangePasswordValSchema(strict=True)
        data = schema.load(request.get_json()).data
        old_password = data['old_password']
        new_password = data['new_password']
        user = User.query.filter_by(id=uid).first()
        if not user:
            return ErrorResponse(USER_NOT_EXIST).make()
        if not user.check_password(old_password):
            return ErrorResponse(USER_RAWPASSWORD_ERROR).make()
        User.reset_password(user.id, new_password)
        return SuccessResponse(NotContent)()
    else:
        return ErrorResponse(NOT_LOGIN).make()
Beispiel #17
0
def save_to_wish(isbn):
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.filter_by(id=uid).first()
    if is_isbn_or_key(isbn):
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    if not yushu_book.first:
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    if user.can_save_to_list(str(isbn)):
        with db.auto_commit():
            wish = Wish()
            wish.isbn = isbn
            wish.user_id = user.id
            db.session.add(wish)
    else:
        return ErrorResponse(SAVE_WISH_ERROR).make()
    return SuccessResponse()()
Beispiel #18
0
def save_to_gifts(isbn):
    if is_isbn_or_key(isbn):
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    if not yushu_book.first:
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.get(uid)
    if user.can_save_to_list(isbn):
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.user_id = user.id
            user.beans += Decimal(0.5).quantize(Decimal('0.00'))
            db.session.add(gift)
    else:
        return ErrorResponse(SAVE_BOOK_ERROR).make()
    return SuccessResponse()()
Beispiel #19
0
def search(keyword):
    dict = request.args.to_dict()
    dict.update({'keyword': keyword})
    schema = BookSearchValSchema(strict=True).load(dict)
    data = schema.data
    keyword = data['keyword']
    page = data['page']
    per_page = data['per_page']

    yushu_book = YuShuBook()
    if is_isbn_or_key(keyword):
        yushu_book.search_by_keyword(keyword, page, per_page)
    else:
        yushu_book.search_by_isbn(keyword)
    pagination = {
        'total': yushu_book.total,
        'current_page': page,
        'per_page': per_page
    }
    return SuccessResponse(data=yushu_book.books, pagination=pagination)()
Beispiel #20
0
def book_detail(isbn):
    has_in_gifts = False
    has_in_wishes = False

    # 取书籍详情数据
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)

    uid = getattr(g, REQUEST_USER_ID, None)
    if uid:
        if Gift.query.filter_by(user_id=uid,
                                isbn=isbn,
                                launched=False,
                                is_deleted=False).first():
            has_in_gifts = True
        if Wish.query.filter_by(user_id=uid,
                                isbn=isbn,
                                launched=False,
                                is_deleted=False).first():
            has_in_wishes = True

    trade_gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()

    trade_gifts_model = TradeInfo(trade_gifts)
    trade_wishes_model = TradeInfo(trade_wishes)

    book_schema = BookSchema()
    book_data = book_schema.dump(yushu_book.first).data  # type: dict
    has = {'has_in_gifts': has_in_gifts, 'has_in_wishes': has_in_wishes}
    trade = TradeModelSchema()
    gifts = {'gifts': trade.dump(trade_gifts_model).data}
    wishes = {'wishes': trade.dump(trade_wishes_model).data}
    book_data.update(**has, **wishes, **gifts)
    schema = BookDetailViewSchema()
    data = schema.dump(book_data).data
    return SuccessResponse(data=data)()
Beispiel #21
0
def drift_pending(did):
    uid = getattr(g, REQUEST_USER_ID)
    schema = DriftPendingStatusSchema(strict=True)
    status = schema.dump(request.get_json()).data['status']
    with db.auto_commit():
        if status == PendingStatus.Success.value:
            # 邮寄
            drift = Drift.query.filter_by(gifter_id=uid, id=did).first_or_404()
            drift.pending = PendingStatus.Success.value
            gift = Gift.query.filter_by(id=drift.gift_id).first_or_404()
            gift.launched = True
            gift.is_deleted = True

            wish = Wish.query.filter_by(isbn=drift.isbn,
                                        user_id=drift.requester_id,
                                        launched=False).first_or_404()
            wish.launched = True
            wish.is_deleted = True
            requester = User.query.get_or_404(drift.requester_id)
            requester.receive_counter += 1
            gifter = User.query.get_or_404(drift.gifter_id)
            gifter.send_counter += 1
        elif status == PendingStatus.Reject.value:
            # 拒绝 当前用户为赠书者
            drift = Drift.query.filter_by(gifter_id=uid, id=did).first_or_404()
            drift.pending = PendingStatus.Reject.value
            drift.is_deleted = True
            requester = User.query.get_or_404(drift.requester_id)
            requester.beans += Decimal(1).quantize(Decimal('0.00'))
        elif status == PendingStatus.Redraw.value:
            # 撤销 当前用户为索要者
            drift = Drift.query.filter_by(id=did, requester_id=uid).first()
            drift.pending = PendingStatus.Redraw.value
            drift.is_deleted = True
            current_user = User.query.get_or_404(uid)
            current_user.beans += Decimal(1).quantize(Decimal('0.00'))
    return SuccessResponse()()
Beispiel #22
0
def index():
    recent_gifts = Gift.recent()
    schema = BookSchema(only=('title', 'summary', 'author', 'isbn', 'image'))
    recent = [schema.dump(gift.book).data for gift in recent_gifts]
    return SuccessResponse(data=recent)()