예제 #1
0
파일: dal.py 프로젝트: NMendon/bookz
def deactivate_post_from_id(post_id, seller_id, status='D'):
    """
    Deactivate a post based on the post and its seller.
    """
    with session_scope() as db_session:
        db_session.query(Post).filter(Post.id==post_id, Post.seller_id==seller_id).update({
            Post.status: status})
예제 #2
0
파일: dal.py 프로젝트: NMendon/bookz
def get_search_results_for_data(course_id, book_name, author_name, edition):
    if course_id is None:
        raise ValueError('Course ID cannot be empty')
    res = []
    with session_scope() as db_session:
        query_builder = db_session.query(
                CourseBook.id, Book.name.label('book_name'), Book.author, Book.edition,
                Course.name.label('course_name'), Post.price, Post.comments, Post.last_modified_date,
                Seller.email).\
            join(Post, Post.course_book_id == CourseBook.id).\
            join(Seller, Seller.id == Post.seller_id).\
            join(Book, Book.id == CourseBook.book_id). \
            join(Course, Course.id == CourseBook.course_id).\
            filter(CourseBook.course_id == course_id).\
            filter(Post.status == 'A')
        if book_name:
            query_builder = query_builder.filter(Book.name == book_name)
        if author_name:
            query_builder = query_builder.filter(Book.author == author_name)
        if edition:
            query_builder = query_builder.filter(Book.edition == edition)
        # TODO: probably munge the email into backend anonymized thingy..
        for r in query_builder.all():
            res.append({
                'book_name': r.book_name,
                'author': r.author,
                'edition': r.edition,
                'course_name': r.course_name,
                'price': r.price,
                'comments': r.comments,
                'last_modified_date': r.last_modified_date.strftime('%m/%d/%Y'),
                'email': r.email
            })
    return res
예제 #3
0
def get_posts_by_seller_id(seller_id, active=set('A')):
    """
    Returns the seller's posts(only returns the active ones by default.
    """
    results = []
    with session_scope() as db_session:
        res = db_session.query(Post.id,  Course.name, Book.name, Book.author, Book.edition, Post.price, Post.comments,
                               Post.last_modified_date). \
            join(CourseBook, Post.course_book_id == CourseBook.id). \
            join(Course, Course.id == CourseBook.course_id). \
            join(Book, Book.id == CourseBook.book_id). \
            filter(Post.seller_id == seller_id). \
            filter(Post.status == 'A').all()
        for post_id, course_name, book_name, author, edition, price, comments, lmd in res:
            results.append({
                'post_id': post_id,
                'book_name': book_name,
                'author': author,
                'edition': edition,
                'course_name': course_name,
                'price': price,
                'comments': comments,
                'last_modified_date': lmd.strftime('%m/%d/%Y')
            })
    return results
예제 #4
0
def update_post_from_id(post_id,
                        seller_id,
                        price,
                        book_id,
                        course_id,
                        comments=None):
    """
    Given a unique post ID update this function updates it. This is a routine for updating a post for a user.
    """
    with session_scope() as db_session:
        course_book_id = db_session.query(CourseBook.id) \
            .filter(CourseBook.course_id == course_id) \
            .filter(CourseBook.book_id == book_id).all()
        if course_book_id and len(course_book_id) > 0:
            db_session.query(Post).filter(Post.id == post_id,
                                          Post.seller_id == seller_id).update({
                                              'course_book_id':
                                              course_book_id[0][0],
                                              'comments':
                                              comments,
                                              'price':
                                              price,
                                              'last_modified_date':
                                              dt.utcnow()
                                          })
        else:
            raise ValueError(post_id, seller_id, price, book_id, course_id,
                             comments)
            _LOGGER.warn("No course book id found")
예제 #5
0
파일: dal.py 프로젝트: NMendon/bookz
def get_posts_by_seller_id(seller_id, active=set('A')):
    """
    Returns the seller's posts(only returns the active ones by default.
    """
    results = []
    with session_scope() as db_session:
        res = db_session.query(Post.id,  Course.name, Book.name, Book.author, Book.edition, Post.price, Post.comments,
                               Post.last_modified_date). \
            join(CourseBook, Post.course_book_id == CourseBook.id). \
            join(Course, Course.id == CourseBook.course_id). \
            join(Book, Book.id == CourseBook.book_id). \
            filter(Post.seller_id == seller_id). \
            filter(Post.status == 'A').all()
        for post_id, course_name, book_name, author, edition, price, comments, lmd in res:
            results.append({
                'post_id': post_id,
                'book_name': book_name,
                'author': author,
                'edition': edition,
                'course_name': course_name,
                'price': price,
                'comments': comments,
                'last_modified_date': lmd.strftime('%m/%d/%Y')
            })
    return results
예제 #6
0
def add_book():
    oauth_token = session.get('oauth_token')
    if oauth_token is None or not session.get('seller_id', None):
        return redirect('authorization/' + session['provider'])
    # Else return the page with the list of courses loaded in
    if request.method == "POST":
        if not request.form:
            raise ValueError("Expected a form in the request")
        _LOGGER.info(request.form)
        form = BookForm(request.form)
        if form.validate():
            with session_scope() as db_session:
                cbid = dal.get_course_book_id_by_course_book_name(
                    int(form.course.data), form.book.data, form.author.data,
                    form.edition.data)
                if cbid:
                    post = Post(seller_id=session.get('seller_id'),
                                course_book_id=cbid.pop(),
                                comments=form.comments.data,
                                price=form.price.data,
                                created_date=dt.datetime.utcnow(),
                                last_modified_date=dt.datetime.utcnow())
                    db_session.add(post)
                else:
                    raise ValueError(
                        "Uh oh.. cbid not found for course_id = %s book_id = %s"
                        % (form.course.data, form.book.data))
            return redirect('/seller_page/' + session['provider'])
        else:
            _LOGGER.warn("Errors: %s " % form.errors)
            return render_template('add_book.html',
                                   form=form,
                                   form_errors=form.errors)
    elif request.method == "GET":
        return render_template('add_book.html')
예제 #7
0
파일: app.py 프로젝트: NMendon/bookz
def add_book():
    oauth_token = session.get('oauth_token')
    if oauth_token is None or not session.get('seller_id', None):
        return redirect('authorization/' + session['provider'])
    # Else return the page with the list of courses loaded in
    if request.method == "POST":
        if not request.form:
            raise ValueError("Expected a form in the request")
        _LOGGER.info(request.form)
        form = BookForm(request.form)
        if form.validate():
            with session_scope() as db_session:
                cbid = dal.get_course_book_id_by_course_book_name(
                    int(form.course.data), form.book.data, form.author.data, form.edition.data)
                if cbid:
                    post = Post(
                        seller_id=session.get('seller_id'),
                        course_book_id=cbid.pop(), comments=form.comments.data, price=form.price.data,
                        created_date=dt.datetime.utcnow(), last_modified_date=dt.datetime.utcnow())
                    db_session.add(post)
                else:
                    raise ValueError(
                        "Uh oh.. cbid not found for course_id = %s book_id = %s" %(
                        form.course.data, form.book.data))
            return redirect('/seller_page/' + session['provider'])
        else:
            _LOGGER.warn("Errors: %s " % form.errors)
            return render_template('add_book.html', form=form, form_errors=form.errors)
    elif request.method == "GET":
        return render_template('add_book.html')
예제 #8
0
def create_post_entry(email='*****@*****.**',
                      seller_name='Sidharth G    upta'):
    with session_scope() as session:
        test_model.create_random_seller_entry(session,
                                              email=email,
                                              seller_name=seller_name)
    return True
예제 #9
0
def deactivate_post_from_id(post_id, seller_id, status='D'):
    """
    Deactivate a post based on the post and its seller.
    """
    with session_scope() as db_session:
        db_session.query(Post).filter(Post.id == post_id,
                                      Post.seller_id == seller_id).update(
                                          {Post.status: status})
예제 #10
0
파일: app.py 프로젝트: NMendon/bookz
def edit_post(post_id):
    """
    Based on the post_id and the seller_id we update the post
    :param post_id:
    :return:
    """
    oauth_token = session.get('oauth_token')
    session_id = session.get('seller_id', None)
    if oauth_token is None or not session_id:
        return redirect('authorization/' + session['provider'])
    if request.method == "GET":
        with session_scope() as db_session:
            res = db_session.query(
                    CourseBook.course_id, Course.name.label('course_name'), CourseBook.book_id,
                    Book.name.label('book_name'), Book.author,
                    Book.ean, Book.edition, Post.comments, Post.price).\
                join(Course, Course.id==CourseBook.course_id).\
                join(Post, Post.course_book_id==CourseBook.id).\
                join(Book, Book.id==CourseBook.book_id).\
                filter(Post.id == post_id).\
                filter(Post.seller_id == session_id).\
                all()
            if res and res[0]:
                _LOGGER.info(res[0])
                return render_template('edit_post.html', post={
                    'post_id': post_id,
                    'book': {
                        'id': res[0].book_id,
                        'name': res[0].book_name
                    },
                    'course': {
                        'id': res[0].course_id,
                        'name': res[0].course_name
                    },
                    'author': res[0].author,
                    'edition': res[0].edition,
                    'price': res[0].price,
                    'comments': res[0].comments,
                    'provider': session['provider']
                })

            else:
                return redirect('seller_page'+session['provider'])
    elif request.method == "POST":
        if not request.form:
            raise ValueError("Expected a form in the request")
        form = BookForm(request.form)
        if form.validate():
            dal.update_post_from_id(
                post_id, session['seller_id'], price=form.price.data,
                book_id=form.book.data, course_id=form.course.data, comments=form.comments.data)
        elif 'price' in form.errors and len(form.errors) == 1:
            # The price was incorrect
            flash('%s (Price)' % form.errors['price'][0])
            _LOGGER.info("Could not validate form %s" % form.errors)
        # TODO: display an error message instead?
        return redirect('seller_page/' + session['provider'])
예제 #11
0
파일: dal.py 프로젝트: NMendon/bookz
def get_author_for_course_id_book_name(course_id, book_name):
    s = set()
    with session_scope() as db_session:
        res = db_session.query(Book.author).\
            join(CourseBook, CourseBook.book_id == Book.id).\
            filter(Book.name == book_name). \
            filter(CourseBook.course_id == course_id).\
            all();
        s.update(r.author for r in res)
    return s
예제 #12
0
def get_author_for_course_id_book_name(course_id, book_name):
    s = set()
    with session_scope() as db_session:
        res = db_session.query(Book.author).\
            join(CourseBook, CourseBook.book_id == Book.id).\
            filter(Book.name == book_name). \
            filter(CourseBook.course_id == course_id).\
            all()
        s.update(r.author for r in res)
    return s
예제 #13
0
파일: dal.py 프로젝트: NMendon/bookz
def get_books_for_course(course_id):
    """
    Return books for a specified course id
    """
    s = set()
    with session_scope() as db_session:
        res = db_session.query(Book.name).\
            join(CourseBook, CourseBook.book_id == Book.id).\
            filter(CourseBook.course_id == course_id).all();
        s.update(r.name for r in res)
    return s
예제 #14
0
파일: app.py 프로젝트: NMendon/bookz
def fetch_courses():
    # oauth_token = session.get('oauth_token')
    # if oauth_token is None:
    #     return redirect('authorization/' + session['provider'])
    courses = []
    with session_scope() as db_session:
        res = db_session.query(Course.id, Course.name, Course.desc).all()
        _LOGGER.debug("Courses: %s " % res)
        for _id, name, desc in res:
            courses.append({"value": _id, "label": name, "desc": desc})
    return json.dumps(courses)
예제 #15
0
def get_books_for_course(course_id):
    """
    Return books for a specified course id
    """
    s = set()
    with session_scope() as db_session:
        res = db_session.query(Book.name).\
            join(CourseBook, CourseBook.book_id == Book.id).\
            filter(CourseBook.course_id == course_id).all()
        s.update(r.name for r in res)
    return s
예제 #16
0
def fetch_courses():
    # oauth_token = session.get('oauth_token')
    # if oauth_token is None:
    #     return redirect('authorization/' + session['provider'])
    courses = []
    with session_scope() as db_session:
        res = db_session.query(Course.id, Course.name, Course.desc).all()
        _LOGGER.debug("Courses: %s " % res)
        for _id, name, desc in res:
            courses.append({"value": _id, "label": name, "desc": desc})
    return json.dumps(courses)
예제 #17
0
파일: dal.py 프로젝트: NMendon/bookz
def post_from_course_book_id(
        seller_id, course_id, book_id, price, comments=None):
    """
    Use this for generating a post ID you want to add to the DB
    """
    with session_scope() as db_session:
        course_book_id = db_session.query(CourseBook.id) \
            .filter(CourseBook.course_id == course_id) \
            .filter(CourseBook.book_id == book_id).all()
        if course_book_id and len(course_book_id) > 0:
            post = Post(
                seller_id=seller_id,
                course_book_id=course_book_id[0][0], comments=comments, price=price)
예제 #18
0
파일: dal.py 프로젝트: NMendon/bookz
def get_course_book_id_by_course_book_name(course_id, book_name, author_name, edition):
    s = set()
    with session_scope() as db_session:
        res = db_session.query(CourseBook.id).\
            join(Book, Book.id == CourseBook.book_id). \
            join(Course, Course.id == CourseBook.course_id). \
            filter(Book.name == book_name). \
            filter(CourseBook.course_id == course_id).\
            filter(Book.author == author_name). \
            filter(Book.edition == edition).\
            all();
        s.update(r.id for r in res)
    return s
예제 #19
0
def fetch_author_for_course_book():
    # app.logger.info(request)
    # oauth_token = session.get('oauth_token')
    # if oauth_token is None:
    #     return redirect('authorization/' + session['provider'])
    course = request.args.get('course')
    book = request.args.get('book')
    if not course or not book:
        _LOGGER.warn('Looks like you navigated to this route incorrectly')
        return ''
    with session_scope() as db_session:
        results = dal.get_author_for_course_id_book_name(course, book)
    return json.dumps(_list_dd_json(results))
예제 #20
0
파일: app.py 프로젝트: NMendon/bookz
def fetch_author_for_course_book():
    # app.logger.info(request)
    # oauth_token = session.get('oauth_token')
    # if oauth_token is None:
    #     return redirect('authorization/' + session['provider'])
    course = request.args.get('course')
    book = request.args.get('book')
    if not course or not book:
        _LOGGER.warn('Looks like you navigated to this route incorrectly')
        return ''
    with session_scope() as db_session:
        results = dal.get_author_for_course_id_book_name(course, book)
    return json.dumps(_list_dd_json(results))
예제 #21
0
def get_course_book_id_by_course_book_name(course_id, book_name, author_name,
                                           edition):
    s = set()
    with session_scope() as db_session:
        res = db_session.query(CourseBook.id).\
            join(Book, Book.id == CourseBook.book_id). \
            join(Course, Course.id == CourseBook.course_id). \
            filter(Book.name == book_name). \
            filter(CourseBook.course_id == course_id).\
            filter(Book.author == author_name). \
            filter(Book.edition == edition).\
            all()
        s.update(r.id for r in res)
    return s
예제 #22
0
파일: app.py 프로젝트: NMendon/bookz
def fetch_course_books():
    # app.logger.info(request)
    # oauth_token = session.get('oauth_token')
    # if oauth_token is None:
    #     return redirect('authorization/' + session['provider'])
    course = request.args.get('course')
    if not course:
        raise ValueError('Looks like you navigated to this route incorrectly')
    # Now get the books
    results = []
    with session_scope() as db_session:
        results = dal.get_books_for_course(course)
    _LOGGER.info("Results: %s " % results)
    return json.dumps(_list_dd_json(results))
예제 #23
0
def fetch_course_books():
    # app.logger.info(request)
    # oauth_token = session.get('oauth_token')
    # if oauth_token is None:
    #     return redirect('authorization/' + session['provider'])
    course = request.args.get('course')
    if not course:
        raise ValueError('Looks like you navigated to this route incorrectly')
    # Now get the books
    results = []
    with session_scope() as db_session:
        results = dal.get_books_for_course(course)
    _LOGGER.info("Results: %s " % results)
    return json.dumps(_list_dd_json(results))
예제 #24
0
파일: dal.py 프로젝트: NMendon/bookz
def update_post_from_id(post_id, seller_id, price, book_id, course_id, comments=None):
    """
    Given a unique post ID update this function updates it. This is a routine for updating a post for a user.
    """
    with session_scope() as db_session:
        course_book_id = db_session.query(CourseBook.id) \
            .filter(CourseBook.course_id == course_id) \
            .filter(CourseBook.book_id == book_id).all()
        if course_book_id and len(course_book_id) > 0:
            db_session.query(Post).filter(Post.id==post_id, Post.seller_id==seller_id).update({
                'course_book_id': course_book_id[0][0],
                'comments': comments, 'price': price,
                'last_modified_date': dt.utcnow()})
        else:
            raise ValueError(post_id, seller_id, price, book_id, course_id, comments)
            _LOGGER.warn("No course book id found")
예제 #25
0
def post_from_course_book_id(seller_id,
                             course_id,
                             book_id,
                             price,
                             comments=None):
    """
    Use this for generating a post ID you want to add to the DB
    """
    with session_scope() as db_session:
        course_book_id = db_session.query(CourseBook.id) \
            .filter(CourseBook.course_id == course_id) \
            .filter(CourseBook.book_id == book_id).all()
        if course_book_id and len(course_book_id) > 0:
            post = Post(seller_id=seller_id,
                        course_book_id=course_book_id[0][0],
                        comments=comments,
                        price=price)
예제 #26
0
def sellers_page(provider):
    # If we already have the access token we can fetch resources.
    # This means step 3 of the 3 legged oauth handshake was completed.
    # We attempt to display the sellers page with his information
    # TODO: validate that the provider is in the list of valid providers as well
    oauth_config = oauth_utils.get_oauth_config_wrapper(app, provider=provider)
    oauth_token = session.get('oauth_token')
    if oauth_token is None:
        return redirect('authorization/' + provider)
    # We use this provider everywhere to get the oauth token
    # Perhaps we should encapsulate it?
    session['provider'] = provider
    # Back here after step 3
    try:
        # TODO: Need this to be based on the type of provider
        google = OAuth2Session(client_id=oauth_config.client_id,
                               token=oauth_token)
        user_info_response = google.get(oauth_config.user_info_uri)
    except Exception as e:
        _LOGGER.info(e)
        return redirect('/authorization/' + provider)
    user_info = user_info_response.json()

    seller_id = None

    with session_scope() as db_session:
        this_user = Seller(name=user_info['name'], email=user_info['email'])
        that_user = db_session.query(Seller).filter_by(
            email=user_info['email']).first()
        if not that_user or that_user.email != user_info['email']:
            db_session.add(this_user)
            db_session.flush()  # We need this ID
            _LOGGER.warn("Adding a user {} to the session".format(that_user))
            seller_id = this_user.id
        else:
            _LOGGER.info("User already exists %s" % that_user)
            seller_id = that_user.id

    session['seller_id'] = seller_id
    results = dal.get_posts_by_seller_id(seller_id)
    return render_template('sellers_page.html',
                           user_info=user_info,
                           results=results,
                           provider=provider)
예제 #27
0
def get_search_results_for_data(course_id, book_name, author_name, edition):
    if course_id is None:
        raise ValueError('Course ID cannot be empty')
    res = []
    with session_scope() as db_session:
        query_builder = db_session.query(
                CourseBook.id, Book.name.label('book_name'), Book.author, Book.edition,
                Course.name.label('course_name'), Post.price, Post.comments, Post.last_modified_date,
                Seller.email).\
            join(Post, Post.course_book_id == CourseBook.id).\
            join(Seller, Seller.id == Post.seller_id).\
            join(Book, Book.id == CourseBook.book_id). \
            join(Course, Course.id == CourseBook.course_id).\
            filter(CourseBook.course_id == course_id).\
            filter(Post.status == 'A')
        if book_name:
            query_builder = query_builder.filter(Book.name == book_name)
        if author_name:
            query_builder = query_builder.filter(Book.author == author_name)
        if edition:
            query_builder = query_builder.filter(Book.edition == edition)
        # TODO: probably munge the email into backend anonymized thingy..
        for r in query_builder.all():
            res.append({
                'book_name':
                r.book_name,
                'author':
                r.author,
                'edition':
                r.edition,
                'course_name':
                r.course_name,
                'price':
                r.price,
                'comments':
                r.comments,
                'last_modified_date':
                r.last_modified_date.strftime('%m/%d/%Y'),
                'email':
                r.email
            })
    return res
예제 #28
0
파일: app.py 프로젝트: NMendon/bookz
def sellers_page(provider):
    # If we already have the access token we can fetch resources.
    # This means step 3 of the 3 legged oauth handshake was completed.
    # We attempt to display the sellers page with his information
    # TODO: validate that the provider is in the list of valid providers as well
    oauth_config = oauth_utils.get_oauth_config_wrapper(app, provider=provider)
    oauth_token = session.get('oauth_token')
    if oauth_token is None:
        return redirect('authorization/'+provider)
    # We use this provider everywhere to get the oauth token
    # Perhaps we should encapsulate it?
    session['provider'] = provider
    # Back here after step 3
    try:
        # TODO: Need this to be based on the type of provider
        google = OAuth2Session(
            client_id=oauth_config.client_id, token=oauth_token)
        user_info_response = google.get(oauth_config.user_info_uri)
    except Exception as e:
        _LOGGER.info(e)
        return redirect('/authorization/' + provider)
    user_info=user_info_response.json()

    seller_id = None

    with session_scope() as db_session:
        this_user = Seller(name=user_info['name'], email=user_info['email'])
        that_user = db_session.query(Seller).filter_by(email=user_info['email']).first()
        if not that_user or that_user.email != user_info['email']:
            db_session.add(this_user)
            db_session.flush() # We need this ID
            _LOGGER.warn("Adding a user {} to the session".format(that_user))
            seller_id = this_user.id
        else:
            _LOGGER.info("User already exists %s" % that_user)
            seller_id = that_user.id

    session['seller_id'] = seller_id
    results = dal.get_posts_by_seller_id(seller_id)
    return render_template(
        'sellers_page.html', user_info=user_info, results=results, provider=provider)
예제 #29
0
def edit_post(post_id):
    """
    Based on the post_id and the seller_id we update the post
    :param post_id:
    :return:
    """
    oauth_token = session.get('oauth_token')
    session_id = session.get('seller_id', None)
    if oauth_token is None or not session_id:
        return redirect('authorization/' + session['provider'])
    if request.method == "GET":
        with session_scope() as db_session:
            res = db_session.query(
                    CourseBook.course_id, Course.name.label('course_name'), CourseBook.book_id,
                    Book.name.label('book_name'), Book.author,
                    Book.ean, Book.edition, Post.comments, Post.price).\
                join(Course, Course.id==CourseBook.course_id).\
                join(Post, Post.course_book_id==CourseBook.id).\
                join(Book, Book.id==CourseBook.book_id).\
                filter(Post.id == post_id).\
                filter(Post.seller_id == session_id).\
                all()
            if res and res[0]:
                _LOGGER.info(res[0])
                return render_template('edit_post.html',
                                       post={
                                           'post_id': post_id,
                                           'book': {
                                               'id': res[0].book_id,
                                               'name': res[0].book_name
                                           },
                                           'course': {
                                               'id': res[0].course_id,
                                               'name': res[0].course_name
                                           },
                                           'author': res[0].author,
                                           'edition': res[0].edition,
                                           'price': res[0].price,
                                           'comments': res[0].comments,
                                           'provider': session['provider']
                                       })

            else:
                return redirect('seller_page' + session['provider'])
    elif request.method == "POST":
        if not request.form:
            raise ValueError("Expected a form in the request")
        form = BookForm(request.form)
        if form.validate():
            dal.update_post_from_id(post_id,
                                    session['seller_id'],
                                    price=form.price.data,
                                    book_id=form.book.data,
                                    course_id=form.course.data,
                                    comments=form.comments.data)
        elif 'price' in form.errors and len(form.errors) == 1:
            # The price was incorrect
            flash('%s (Price)' % form.errors['price'][0])
            _LOGGER.info("Could not validate form %s" % form.errors)
        # TODO: display an error message instead?
        return redirect('seller_page/' + session['provider'])
예제 #30
0
def create_post_entry(email='*****@*****.**', seller_name='Sidharth G    upta'):
    with session_scope() as session:
        test_model.create_random_seller_entry(session, email=email, seller_name=seller_name)
    return True