示例#1
0
def save_upload_file(file, user_id, subdir):
    if isAllowedFile(file.filename):
        if file is not None:
            UPLOAD_SUBFOLDER = str(user_id) + '/' + subdir
            UPLOAD_FOLDER = os.getcwd() + '/uploads'
            UPLOAD_FOLDER = os.path.join(UPLOAD_FOLDER, UPLOAD_SUBFOLDER)
            if not os.path.exists(UPLOAD_FOLDER):
                os.makedirs(UPLOAD_FOLDER)
            savepath = os.path.join(UPLOAD_FOLDER,
                                    secure_filename(file.filename))
            log("User %s uploaded %s to %s" %
                (user_id, secure_filename(file.filename), savepath))
            file.save(savepath)
            if subdir == COVER_IMAGES_SUBDIR:
                return JSONResponse(
                    dumps({
                        'cover_image_url':
                        "%s%s/%s" % (BASE_URL, UPLOAD_SUBFOLDER,
                                     secure_filename(file.filename))
                    }))
            else:
                return JSONResponse(
                    dumps({
                        'head_image_url':
                        "%s%s/%s" % (BASE_URL, UPLOAD_SUBFOLDER,
                                     secure_filename(file.filename))
                    }))
        else:
            return JSONResponse(dumps({'message': "Null file provided."}), 400)
    else:
        return JSONResponse(dumps({'message': 'Not allowed file format.'}),
                            400)
示例#2
0
def del_books_from_category(user_id, category_id, book_int_or_list):
    delresult = None
    if not isCategoryExist(user_id, category_id):
        return JSONResponse(
            jsonify({'message': "category %s not found." % category_id}), 404)
    if type(book_int_or_list) is int:
        delresult = categorysdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'category_id': category_id
            }]}, {'$pull': {
                'book_list': book_int_or_list
            }})
    elif type(book_int_or_list) is list:
        delresult = categorysdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'category_id': category_id
            }]}, {'$pullAll': {
                'book_list': book_int_or_list
            }})
    else:
        return JSONResponse(
            jsonify({'message': 'Please provide correct data format.'}), 400)
    return JSONResponse(dumps(delresult))
示例#3
0
def get_book_by_id(user_id, book_id):
    if not isBookExist(user_id, book_id):
        return JSONResponse(
            jsonify({'message': "book %s not found." % (book_id)}), 404)
    tmpbook = booksdb.find_one(
        {'$and': [{
            'user_id': user_id
        }, {
            'book_id': book_id
        }]})
    bookscategories = categorysdb.find({
        '$and': [{
            'user_id': user_id
        }, {
            'deleted': False
        }, {
            'book_list': book_id
        }]
    }).sort('category_id', 1)
    book = json.loads(dumps(tmpbook))
    categoiesjson = json.loads(dumps(bookscategories))
    book['category_id'] = list()
    for category in categoiesjson:
        book['category_id'].append(category['category_id'])
    return JSONResponse(book)
示例#4
0
def add_book(user_id,
             bookname,
             author="",
             publisher="",
             publish_date="",
             price=0,
             ISBN="",
             tags=[],
             cover_image_url='http://i.imgur.com/zNPKpwk.jpg',
             category=[]):
    new_book_id = 1
    tmpbooks = booksdb.find().sort([('book_id', -1)]).limit(1)
    for book in tmpbooks:
        lastbook = book
    if lastbook['user_id'] is not None:
        new_book_id = int(lastbook['book_id']) + 1
    nowtime = time.time()
    if price == "":
        price = 0

    tmpbook = {
        'book_id': new_book_id,
        'bookname': bookname,
        'author': author,
        'publisher': publisher,
        'publish_date': publish_date,
        'price': float(price),
        'ISBN': ISBN,
        'user_id': user_id,
        'tags': tags,
        'cover_image_url': cover_image_url,
        'deleted': False,
        'create_time': nowtime,
        'update_time': nowtime,
    }
    booksdb.insert(tmpbook)
    if type(category) is list:
        addresult = JSONResponse()
        for category_id in category:
            addresult = add_books_to_category(user_id, category_id,
                                              new_book_id)
    elif type(category) is int:
        addresult = add_books_to_category(user_id, category, new_book_id)
    if int(addresult.response_code) / 100 != 2:
        return addresult

    if type(category) is list:
        tmpbook[
            'category_id'] = category  # category data is stored in categorysdb, so it is not inserted to booksdb.
    elif type(category) is int:
        tmpbook['category_id'] = list()
        tmpbook['category_id'].append(category)
    log("User %s created a book, id=%s, bookname=\"%s\", author=\"%s\", publisher=\"%s\", publish_date=\"%s\", price=\"%s\", ISBN=\"%s\" tags=\"%s\", create_time=\"%s\", update_time=\"%s\", categoey=\"%s\""
        % (user_id, new_book_id, bookname, author, publisher, publish_date,
           price, ISBN, tags, nowtime, nowtime, category))
    return JSONResponse(dumps(tmpbook), 201)
示例#5
0
def get_category_by_id(user_id, category_id):
    if not isCategoryExist(user_id, category_id):
        return JSONResponse(
            jsonify({'message': "category %s not found." % (category_id)}),
            404)
    tmpbooks = categorysdb.find_one(
        {'$and': [{
            'user_id': user_id
        }, {
            'category_id': category_id
        }]})
    return JSONResponse(dumps(tmpbooks))
示例#6
0
def del_category(user_id, category_id):
    if not isCategoryExist(user_id, category_id):
        return JSONResponse(
            jsonify({'message': "category %s not found." % category_id}), 404)
    updateResult = categorysdb.update(
        {'$and': [{
            'user_id': user_id
        }, {
            'category_id': category_id
        }]}, {'$set': {
            'deleted': True
        }})
    log("User %s deleted category %s" % (user_id, category_id))
    return JSONResponse(updateResult)
示例#7
0
def add_books_to_category(user_id, category_id, book_list_or_int):
    if not isCategoryExist(user_id, category_id):
        return JSONResponse(jsonify({'message': 'category not found'}), 404)
    if type(book_list_or_int) is list:
        for book_id in book_list_or_int:
            if not isBookExist(user_id, book_id):
                return JSONResponse(
                    jsonify({
                        'message':
                        'User %s doesn\'t own book %s' % (user_id, book_id)
                    }))
        categorysdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'category_id': category_id
            }]}, {'$addToSet': {
                'book_list': {
                    '$each': book_list_or_int
                }
            }})
    if type(book_list_or_int) is int:
        if not isBookExist(user_id, book_list_or_int):
            return JSONResponse(
                jsonify({
                    'message':
                    'User %s doesn\'t own book %s' %
                    (user_id, book_list_or_int)
                }))
        categorysdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'category_id': category_id
            }]}, {'$addToSet': {
                'book_list': book_list_or_int
            }})
    else:
        return JSONResponse(
            jsonify({'message': 'Wrong book_id data type provided.'}), 400)
    tmpcategory = categorysdb.find_one(
        {'$and': [{
            'user_id': user_id
        }, {
            'category_id': category_id
        }]})
    log("User %s added books %s to category %s" %
        (user_id, book_list_or_int, category_id))
    return JSONResponse(dumps(tmpcategory), 200)
示例#8
0
def getProductInfoByISBN(ISBN):
    resultdict = dict()
    HTML = getHTMLByLink(getProductLink(ISBN))
    info = getProductInfoStr(HTML).encode('utf-8')
    pic = getProductInfoPic(HTML).encode('utf-8')
    bookname = getBookname(HTML).encode('utf-8')
    for s in info.split(','):
        try:
            tmp = s.split(':')
            if tmp[0] == '譯者':
                resultdict['translater'] = tmp[1]
            elif tmp[0] == 'ISBN':
                resultdict['ISBN'] = tmp[1]
            elif tmp[0] == '原文名稱':
                resultdict['original_bookname'] = tmp[1]
            elif tmp[0] == '類別':
                resultdict['category'] = tmp[1]
            elif tmp[0] == '語言':
                resultdict['language'] = tmp[1]
            elif tmp[0] == '作者':
                resultdict['author'] = tmp[1]
            elif tmp[0] == '出版社':
                resultdict['publisher'] = tmp[1]
            elif tmp[0] == '頁數':
                resultdict['pages'] = tmp[1]
            elif tmp[0] == '出版日期':
                resultdict['publish_date'] = tmp[1].replace('/', '')
            # resultdict[tmp[0]] = tmp[1]
        except Exception:
            pass
    resultdict['bookname'] = bookname
    resultdict['cover_image_url'] = pic
    return JSONResponse(resultdict)
示例#9
0
def list_all_category(user_id):
    tmpcategorys = categorysdb.find({
        '$and': [{
            'user_id': user_id
        }, {
            'deleted': False
        }]
    }).sort('category_id', 1)
    return JSONResponse(dumps(tmpcategorys))
示例#10
0
def update_category(user_id, cataogry_id, category_name=""):
    if not isCategoryExist(user_id, cataogry_id):
        return JSONResponse(
            jsonify({'message': "category %s not found." % (cataogry_id)}),
            404)
    updated = None
    if category_name != "":
        oldCatagory = categorysdb.find_one({
            '$and': [{
                'user_id': user_id
            }, {
                'category_name': category_name
            }, {
                'deleted': False
            }]
        })
        if oldCatagory is not None:
            return JSONResponse(
                jsonify(
                    {'message': "Catagory %s already exist." % category_name}))
        updated = categorysdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'category_id': cataogry_id
            }]}, {'$set': {
                'category_name': category_name
            }})
        if updated is not None:
            log("Updated user %s's category %s's category_name to %s" %
                (user_id, cataogry_id, category_name))
    tmpbook = categorysdb.find_one(
        {'$and': [{
            'user_id': user_id
        }, {
            'category_id': cataogry_id
        }]})  # Get updated data.
    return JSONResponse(dumps(tmpbook))
示例#11
0
def del_book(user_id, book_id):
    if not isBookExist(user_id, book_id):
        return JSONResponse(
            jsonify({'message': "book %s not found." % (book_id)}), 404)
    allcategories = categorysdb.find({
        '$and': [{
            'user_id': user_id
        }, {
            'book_list': book_id
        }]
    }).sort('category_id', 1)
    for category in allcategories:
        del_books_from_category(user_id, category['category_id'], book_id)
    updateResult = booksdb.update(
        {'$and': [{
            'user_id': user_id
        }, {
            'book_id': book_id
        }]}, {'$set': {
            'deleted': True
        }})
    log("User %s deleted book %s" % (user_id, book_id))
    return JSONResponse(updateResult)
示例#12
0
def add_category(user_id, category_name):
    oldCatagory = categorysdb.find_one({
        '$and': [{
            'user_id': user_id
        }, {
            'category_name': category_name
        }, {
            'deleted': False
        }]
    })
    if oldCatagory is not None:
        return JSONResponse(
            jsonify({'message': "Catagory %s already exist." % category_name}),
            403)

    new_category_id = 1
    lastcata = dict()
    lastcata['category_id'] = 1
    tmpcatas = categorysdb.find().sort([('category_id', -1)]).limit(1)
    for cata in tmpcatas:
        lastcata = cata
    if lastcata['category_id'] is not None:
        new_category_id = int(lastcata['category_id']) + 1

    category = {
        'category_id': new_category_id,
        'category_name': category_name,
        'user_id': user_id,
        'book_list': [],
        'deleted': False
    }

    categorysdb.insert(category)
    log("User %s created a category, category_id = %s , category_name = %s" %
        (user_id, new_category_id, category_name))
    return JSONResponse(dumps(category), 201)
示例#13
0
def list_all_books(user_id):
    tmpbooks = booksdb.find({
        '$and': [{
            'user_id': user_id
        }, {
            'deleted': False
        }]
    }).sort('book_id', 1)
    bookscategories = categorysdb.find({
        '$and': [{
            'user_id': user_id
        }, {
            'deleted': False
        }]
    }).sort('category_id', 1)
    booksjson = json.loads(dumps(tmpbooks))
    categoiesjson = json.loads(dumps(bookscategories))
    for book in booksjson:
        book['category_id'] = list()
        for category in categoiesjson:
            if book['book_id'] in category['book_list']:
                book['category_id'].append(category['category_id'])
    return JSONResponse(dumps(booksjson))
示例#14
0
def searchProductInfoListByBookname(bookname):
    resultlist = list()
    for link in removeTwiceDuplicated(getProductLinksList(bookname)):
        resultdict = dict()
        HTML = getHTMLByLink(link)
        info = getProductInfoStr(HTML).encode('utf-8')
        pic = getProductInfoPic(HTML).encode('utf-8')
        for s in info.split(','):
            try:
                tmp = s.split(':')
                if tmp[0] == '譯者':
                    resultdict['translater'] = tmp[1]
                elif tmp[0] == 'ISBN':
                    resultdict['ISBN'] = tmp[1]
                elif tmp[0] == '原文名稱':
                    resultdict['original_bookname'] = tmp[1]
                elif tmp[0] == '類別':
                    resultdict['category'] = tmp[1]
                elif tmp[0] == '語言':
                    resultdict['language'] = tmp[1]
                elif tmp[0] == '作者':
                    resultdict['author'] = tmp[1]
                elif tmp[0] == '出版社':
                    resultdict['publisher'] = tmp[1]
                elif tmp[0] == '書名':
                    resultdict['bookname'] = tmp[1]
                elif tmp[0] == '頁數':
                    resultdict['pages'] = tmp[1]
                elif tmp[0] == '出版日期':
                    resultdict['publish_date'] = tmp[1]
                #resultdict[tmp[0]] = tmp[1]
            except Exception:
                pass
        resultdict['cover_image_url'] = pic
        resultlist.append(resultdict)

    return JSONResponse(resultlist)
示例#15
0
from json import dumps
from views.templates.JSONResponse import JSONResponse
JSONResponseProvideNecessaryInfo = JSONResponse(
    dumps({'message': 'Please provide all necessary info.'}), 400)
JSONResponseLoginSuccessful = JSONResponse(
    dumps({'message': "Login successful"}))
JSONResponseWrongPassword = JSONResponse(dumps({'message': "Wrong password."}),
                                         403)
from views.templates.JSONResponse import JSONResponse
from json import dumps
__author__ = 'Ikaros'
JSONREsponseTokenExpired = JSONResponse(dumps({'message': "Token expired"}),
                                        403)
JSONResponseTokenNotFound = JSONResponse(
    dumps({'message': "Token not found."}), 404)
示例#17
0
def update_book(user_id,
                book_id,
                bookname="",
                author="",
                publisher="",
                publish_date="",
                price=0,
                ISBN="",
                tags=[],
                cover_image_url=""):
    if not isBookExist(user_id, book_id):
        return JSONResponse(
            jsonify({'message': "book %s not found." % (book_id)}), 404)
    updated = 0
    if bookname != "":
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'bookname': bookname
            }})
        log("Updated user %s's book %s's bookname to %s" %
            (user_id, book_id, bookname))
    if author != "":
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'author': author
            }})
        log("Updated user %s's book %s's author to %s" %
            (user_id, book_id, author))
    if publisher != "":
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'publisher': publisher
            }})
        log("Updated user %s's book %s's publisher to %s" %
            (user_id, book_id, publisher))
    if publish_date != "":
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'publish_date': publish_date
            }})
        log("Updated user %s's book %s's publish_date to %s" %
            (user_id, book_id, publish_date))
    if price != 0:
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'price': float(price)
            }})
        log("Updated user %s's book %s's price to %s" %
            (user_id, book_id, price))
    if ISBN != "":
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'ISBN': ISBN
            }})
        log("Updated user %s's book %s's ISBN to %s" %
            (user_id, book_id, ISBN))
    if tags:
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'tags': tags
            }})
        log("Updated user %s's book %s's tags to %s" %
            (user_id, book_id, tags))
    if cover_image_url != "":
        updated = booksdb.update(
            {'$and': [{
                'user_id': user_id
            }, {
                'book_id': book_id
            }]}, {'$set': {
                'cover_image_url': cover_image_url
            }})
        log("Updated user %s's book %s's cover_image_url to %s" %
            (user_id, book_id, cover_image_url))
    if updated:
        nowtime = time.time()
        booksdb.update({'$and': [{
            'user_id': user_id
        }, {
            'book_id': book_id
        }]}, {'$set': {
            'update_time': nowtime
        }})
        log("Updated user %s's book %s's update_time to %s" %
            (user_id, book_id, nowtime))
    return get_book_by_id(user_id, book_id)
示例#18
0
from json import dumps
from views.templates.JSONResponse import JSONResponse

JSONResponseUserNotFound = JSONResponse(dumps({'message': 'User not found.'}),
                                        404)
JSONResponseUserLogoutSuccessful = JSONResponse(
    dumps({'message': 'Logout successful'}), 200)
JSONResponseUserAlreadyExist = JSONResponse(
    dumps({'message': 'User already exists.'}), 403)
JSONResponseUserDeactivated = JSONResponse(
    dumps({'message': 'User already deleted.'}), 403)
from views.templates.JSONResponse import JSONResponse
from bson.json_util import dumps

JSONResponseProvideAtLeastBookName = JSONResponse(
    dumps({'message': 'Please provide at least book name.'}), 400)
JSONResponseBookNotFound = JSONResponse(
    dumps({'message': 'Can\'t found the book.'}), 404)
JSONResponsePriceNotNumber = JSONResponse(
    dumps({'message': 'Price is not a number.'}), 400)
from views.templates.JSONResponse import JSONResponse
from bson.json_util import dumps

JSONResponseLoginFirst = JSONResponse(
    dumps({'message': 'Please log in first.'}), 401)
from views.templates.JSONResponse import JSONResponse
from json import dumps
__author__ = 'Ikaros'
JSONResponseISBNNotFound = JSONResponse(dumps({'message': "ISBN not found"}),
                                        404)
JSONResponsePicNotFound = JSONResponse(dumps({'message': "Pic not found"}),
                                       404)
示例#22
0
from views.templates.JSONResponse import JSONResponse
from json import dumps

JSONResponseLoginFirst = JSONResponse(
    dumps({'message': 'Please log in first.'}), 401)
JSONResponseProvideToken = JSONResponse(
    dumps({'message': 'Please provide token.'}), 401)
JSONResponseInvalidJSON = JSONResponse(
    dumps({'message': 'Invalid JSON request.'}), 400)