Esempio n. 1
0
def listPosts(request):
    __cursor = connection.cursor()
    if request.method != 'GET':
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'request method should be GET'}))
    thread = request.GET.get('thread')
    thread_id = general_utils.validate_id(thread)
    if thread_id is None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'thread id is required'}))
    if thread_id == False:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'thread id should be int'}))
    try:
       thread_id_qs = __cursor.execute(SELECT_THREAD_BY_ID, [thread_id,]) 
    except DatabaseError as db_err:
        __cursor.close() 
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    if not __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'thread was not found'})) 
    thread_id = __cursor.fetchone()[0] 

    get_all_posts_specified_query = SELECT_ALL_POSTS_BY_THREAD
    query_params = [thread_id, ]
    since_date = general_utils.validate_date(request.GET.get('since'))
    if since_date:
        get_all_posts_specified_query += '''AND post.date >= %s '''
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect since_date fromat'}))

    order = request.GET.get('order', 'desc')
    if order.lower() not in ('asc', 'desc'):
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect order parameter: {}'.format(order)}))
    
    get_all_posts_query_postfix = ''' ORDER BY post.{} ''' + order

    sort = request.GET.get('sort', 'flat')
    if sort.lower() not in ('flat', 'tree', 'parent_tree'):
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect sort parameter: {}'.format(sort)}))
    else:
        sort = 'flat'

    if sort == 'flat':
        get_all_posts_query_postfix = get_all_posts_query_postfix.format('date')
    else:
        get_all_posts_query_postfix = get_all_posts_query_postfix.format('hierarchy_id')

    limit = request.GET.get('limit')
    if limit:
        try:
            limit = int(limit)
        except ValueError:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                        'response': 'limit should be int'}))
        if sort == 'flat' or sort == 'tree':
            get_all_posts_specified_query += get_all_posts_query_postfix + ''' LIMIT %s'''
            query_params.append(limit)
        else:
            if order == 'asc':
                operation = '<='
            else:
                operation = '>='
                try:
                    max_posts_number_qs = __cursor.execute(SELECT_TOP_POST_NUMBER, [thread_id,]) 
                except DatabaseError as db_err: 
                    __cursor.close()
                    return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                                'response': unicode(db_err)}))
                if __cursor.rowcount:
                    max_posts_number = __cursor.fetchone()[0]
                else:
                    max_posts_number = 0     
                limit = max_posts_number - limit + 1
                if limit < 1:
                    limit = 1
            get_all_posts_specified_query += "AND post.hierarchy_id {} '{}' ".format(operation, limit) + \
                                              get_all_posts_query_postfix
    else:
        get_all_posts_specified_query += get_all_posts_query_postfix

    try:
        posts_qs = __cursor.execute(get_all_posts_specified_query, query_params) 
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)})) 
    
    posts = []
    for post in __cursor.fetchall():
        posts.append({
            "date": post[0].strftime("%Y-%m-%d %H:%M:%S") ,
            "dislikes": post[1],
            "forum": post[2],
            "id": post[3],
            "isApproved": not not post[4],
            "isDeleted": not not post[5],
            "isEdited": not not post[6],
            "isHighlighted": not not post[7],
            "isSpam": post[8],
            "likes": post[9],
            "message": post[10],
            "parent": post[11],
            "points": post[12],
            "thread": post[13], 
            "user": post[14]
            })
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': posts
                               }))
Esempio n. 2
0
def list_posts(request):
    cursor = connection.cursor()
    if request.method != "GET":
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "request method should be GET"}))
    threadId = codes_and_utils.validate_id(request.GET.get("thread"))
    forum = request.GET.get("forum")
    if threadId is None and forum is None:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "thread id or forum id not found"}))
    if threadId == False:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "thread id should be int"}))
    if threadId and forum:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "you should specify thread OR forum"}))
    if not threadId:
        related_table_name = "forum"
        related_query = SELECT_FORUM_BY_SHORT_NAME
        related_params = [forum]
    else:
        related_table_name = "thread"
        related_query = SELECT_THREAD_BY_ID
        related_params = [threadId]

    try:
        cursor.execute(related_query, related_params)
        if cursor.rowcount == 0:
            cursor.close()
            return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "{} not found".format(related_table_name)}))
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    related_id = cursor.fetchone()[0]
    query_params = [related_id]
    get_post_list_specified_query = SELECT_POSTS_BY_FORUM_OR_THREAD
    since_date = codes_and_utils.validate_date(request.GET.get("since"))
    if since_date:
        get_post_list_specified_query += """AND post.date >= %s """
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect since_date fromat"}))

    order = request.GET.get("order", "desc")
    if order.lower() not in ("asc", "desc"):
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect order parameter: {}".format(order)})
        )

    get_post_list_specified_query += """ORDER BY post.date """ + order

    limit = request.GET.get("limit")
    if limit:
        try:
            limit = int(limit)
        except ValueError:
            cursor.close()
            return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "limit should be int"}))
        get_post_list_specified_query += """ LIMIT %s"""
        query_params.append(limit)

    try:
        cursor.execute(get_post_list_specified_query.format(related_table_name), query_params)
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

    posts = []
    for post in cursor.fetchall():
        posts.append(
            {
                "date": post[0].strftime("%Y-%m-%d %H:%M:%S"),
                "dislikes": post[1],
                "forum": post[2],
                "id": post[3],
                "isApproved": post[4],
                "isDeleted": post[5],
                "isEdited": post[6],
                "isHighlighted": post[7],
                "isSpam": post[8],
                "likes": post[9],
                "message": post[10],
                "parent": post[11],
                "points": post[12],
                "thread": post[13],
                "user": post[14],
            }
        )
    cursor.close()
    return HttpResponse(dumps({"code": codes.OK, "response": posts}))
Esempio n. 3
0
def create(request):
    cursor = connection.cursor()
    try:
        json_request = loads(request.body)
    except ValueError as value_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": unicode(value_err)}))

    try:
        date = json_request["date"]
        threadId = json_request["thread"]
        message = json_request["message"]
        forum = json_request["forum"]
        email = json_request["user"]
    except KeyError as key_err:
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "Not found: {}".format(unicode(key_err))})
        )
    # validate user
    try:
        cursor.execute(SELECT_USER_BY_EMAIL, [email])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

    if cursor.rowcount == 0:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "user not found"}))
    user_id = cursor.fetchone()[0]

    # validate forum
    try:
        cursor.execute(SELECT_FORUM_BY_SHORT_NAME, [forum])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    if cursor.rowcount == 0:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "forum not found"}))
    forum_id = cursor.fetchone()[0]

    # validate thread
    try:
        cursor.execute(SELECT_THREAD_BY_ID, [threadId])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    if cursor.rowcount == 0:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "thread not found"}))
    threadId = cursor.fetchone()[0]

    # validate date
    date = codes_and_utils.validate_date(date)
    if not date:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect date fromat"}))
    # validate message
    if not message:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "message should not be empty"}))

    # validate optional args
    query_params = []
    optional_args = ["isApproved", "isDeleted", "isEdited", "isHighlighted", "isSpam"]
    for optional_arg_name in optional_args:
        optional_arg_value = json_request.get(optional_arg_name)
        if optional_arg_value is not None:
            # print optional_arg_name, optional_arg_value
            if not isinstance(optional_arg_value, bool):
                cursor.close()
                return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "optional flag should be bool"}))
            query_params.append([optional_arg_name, optional_arg_value])

    parentId = json_request.get("parent")

    with transaction.atomic():
        if parentId:
            try:
                cursor.execute(SELECT_PARENT_POST_HIERARCHY, [parentId])
                if cursor.rowcount == 0:
                    cursor.close()
                    return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "parent post not found"}))
                post = cursor.fetchone()
                cursor.execute(UPDATE_CHILD_POST_COUNT, [parentId])
            except DatabaseError as db_err:
                cursor.close()
                return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

            hierarchyId = "{0}{1}/".format(post[2], unicode(post[1] + 1))
        else:
            try:
                cursor.execute(SELECT_TOP_POST_NUMBER, [threadId])
                if cursor.rowcount == 0:
                    cursor.execute(INSERT_TOP_POST_NUMBER, [threadId])
                    post_number = 1
                else:
                    post_number = cursor.fetchone()[0] + 1
                    cursor.execute(UPDATE_POST_NUMBER, [threadId])
            except DatabaseError as db_err:
                cursor.close()
                return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
            hierarchyId = "{}/".format(unicode(post_number))

        try:
            post_qs = cursor.execute(INSERT_POST, [hierarchyId, date, message, user_id, forum_id, threadId, parentId])
            cursor.execute(SELECT_LAST_INSERT_ID, [])
        except DatabaseError as db_err:
            cursor.close()
            return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
        postId = cursor.fetchone()[0]

    update_post_query = UPDATE_POST_PREFIX
    if query_params:
        update_post_query += ", ".join([query_param[0] + "= %s" for query_param in query_params]) + """ WHERE id = %s"""
        try:
            cursor.execute(update_post_query, [query_param[1] for query_param in query_params] + [postId])
        except DatabaseError as db_err:
            cursor.close()
            return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

    try:
        post, realted_ids = get_post_by_id(cursor, postId)
    except TypeError:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": post}))
    if not post["isDeleted"]:
        update_thread_posts(cursor, threadId, 1)
    cursor.close()
    return HttpResponse(dumps({"code": codes.OK, "response": post}))
Esempio n. 4
0
def listPosts(request):
    __cursor = connection.cursor()
    if request.method != 'GET':
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'request method should be GET'}))
    email = request.GET.get('user')
    # validate user
    try:
        user_id_qs = __cursor.execute(SELECT_USER_BY_EMAIL, [email, ])
    except DatabaseError as db_err:
        __cursor.close() 
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))

    if not  __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'user not found'}))
    user_id = __cursor.fetchone()[0]
    query_params = [user_id, ]
    get_post_list_specified_query = SELECT_POSTS_BY_USER
    since_date = general_utils.validate_date(request.GET.get('since'))
    if since_date:
        get_post_list_specified_query += '''AND post.date >= %s '''
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect since_date fromat'}))

    order = request.GET.get('order', 'desc')
    if order.lower() not in ('asc', 'desc'):
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect order parameter: {}'.format(order)}))
    
    get_post_list_specified_query += '''ORDER BY post.date ''' + order

    limit = request.GET.get('limit')
    if limit:
        try:
            limit = int(limit)
        except ValueError:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                        'response': 'limit should be int'}))
        get_post_list_specified_query += ''' LIMIT %s'''
        query_params.append(limit)

    try:
        post_list_qs = __cursor.execute(get_post_list_specified_query, query_params)
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)})) 
    
    posts = []

    for post in __cursor.fetchall():
        posts.append({
            "date": post[0].strftime("%Y-%m-%d %H:%M:%S") ,
            "dislikes": post[1],
            "forum": post[2],
            "id": post[3],
            "isApproved": post[4],
            "isDeleted": post[5],
            "isEdited": post[6],
            "isHighlighted": post[7],
            "isSpam": post[8],
            "likes": post[9],
            "message": post[10],
            "parent": post[11],
            "points": post[12],
            "thread": post[13],
            "user": post[14]
        })
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': posts})) 
Esempio n. 5
0
File: list.py Progetto: niggor/apiDB
def list_threads(request):
    __cursor = connection.cursor()
    if request.method != "GET":
        __cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "request method should be GET"}))
    short_name = request.GET.get("forum")
    email = request.GET.get("user")
    if short_name is None and email is None:
        __cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "thread id or forum id not found"}))
    if short_name and email:
        __cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "you should specify thread OR forum"}))
    if email:
        related_table_name = "user"
        related_query = SELECT_USER_BY_EMAIL
        related_params = [email]
    else:
        related_table_name = "forum"
        related_query = SELECT_FORUM_BY_SHORT_NAME
        related_params = [short_name]
    try:
        __cursor.execute(related_query, related_params)
        if not __cursor.rowcount:
            __cursor.close()
            return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "{} not found".format(related_table_name)}))
    except DatabaseError as db_err:
        __cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    related_id = __cursor.fetchone()[0]
    query_params = [related_id]
    get_thread_list_specified_query = SELECT_THREADS_BY_FORUM_OR_USER
    since_date = general_utils.validate_date(request.GET.get("since"))
    if since_date:
        get_thread_list_specified_query += """AND thread.date >= %s """
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        __cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect since_date fromat"}))

    order = request.GET.get("order", "desc")
    if order.lower() not in ("asc", "desc"):
        __cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect order parameter: {}".format(order)})
        )

    get_thread_list_specified_query += """ORDER BY thread.date """ + order

    limit = request.GET.get("limit")
    if limit:
        try:
            limit = int(limit)
        except ValueError:
            __cursor.close()
            return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "limit should be int"}))
        get_thread_list_specified_query += """ LIMIT %s"""
        query_params.append(limit)

    try:
        threads_qs = __cursor.execute(get_thread_list_specified_query.format(related_table_name), query_params)
    except DatabaseError as db_err:
        __cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

    threads = []
    for thread in __cursor.fetchall():
        threads.append(
            {
                "date": thread[0].strftime("%Y-%m-%d %H:%M:%S"),
                "dislikes": thread[1],
                "forum": thread[2],
                "id": thread[3],
                "isClosed": not not thread[4],
                "isDeleted": not not thread[5],
                "likes": thread[6],
                "message": thread[7],
                "points": thread[8],
                "posts": thread[9],
                "slug": thread[10],
                "title": thread[11],
                "user": thread[12],
            }
        )
    __cursor.close()
    return HttpResponse(dumps({"code": codes.OK, "response": threads}))
Esempio n. 6
0
File: list.py Progetto: niggor/apiDB
def list_posts(request):
    __cursor = connection.cursor()
    if request.method != 'GET':
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'request method should be GET'}))
    thread_id = general_utils.validate_id(request.GET.get('thread'))
    forum = request.GET.get('forum')
    if thread_id is None and forum is None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'thread id or forum id not found'})) 
    if thread_id == False:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'thread id should be int'}))
    if thread_id and forum:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'you should specify thread OR forum'}))
    if thread_id:
        related_table_name = 'thread'
        related_query = SELECT_THREAD_BY_ID 
        related_params = [thread_id, ]
    else:
        related_table_name = 'forum'
        related_query = SELECT_FORUM_BY_SHORT_NAME 
        related_params = [forum, ]     

    try:
        __cursor.execute(related_query, related_params) 
        if not __cursor.rowcount:
            __cursor.close()
            return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                       'response': '{} not found'.format(related_table_name)})) 
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    related_id = __cursor.fetchone()[0]
    query_params = [related_id, ]
    get_post_list_specified_query = SELECT_POSTS_BY_FORUM_OR_THREAD
    since_date = general_utils.validate_date(request.GET.get('since'))
    if since_date:
        get_post_list_specified_query += '''AND post.date >= %s '''
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect since_date fromat'}))

    order = request.GET.get('order', 'desc')
    if order.lower() not in ('asc', 'desc'):
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect order parameter: {}'.format(order)}))
    
    get_post_list_specified_query += '''ORDER BY post.date ''' + order

    limit = request.GET.get('limit')
    if limit:
        try:
            limit = int(limit)
        except ValueError:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                        'response': 'limit should be int'}))
        get_post_list_specified_query += ''' LIMIT %s'''
        query_params.append(limit)

    try:
        __cursor.execute(get_post_list_specified_query.format(related_table_name), 
                         query_params)
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)})) 
    
    posts = []
    for post in __cursor.fetchall():
        posts.append({
            "date": post[0].strftime("%Y-%m-%d %H:%M:%S") ,
            "dislikes": post[1],
            "forum": post[2],
            "id": post[3],
            "isApproved": post[4],
            "isDeleted": post[5],
            "isEdited": post[6],
            "isHighlighted": post[7],
            "isSpam": post[8],
            "likes": post[9],
            "message": post[10],
            "parent": post[11],
            "points": post[12],
            "thread": post[13],
            "user": post[14]
        })
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': posts})) 
Esempio n. 7
0
def listThreads(request):
    cursor = connection.cursor()
    if request.method != "GET":
        cursor.close()
        return HttpResponse(dumps({"code": general_utils.INVALID_QUERY, "response": "request method should be GET"}))
    short_name = request.GET.get("forum")
    if not short_name:
        cursor.close()
        return HttpResponse(dumps({"code": general_utils.INCORRECT_QUERY, "response": "forum name not found"}))
    try:
        cursor.execute(SELECT_FORUM_BY_SHORT_NAME, [short_name])
        if cursor.rowcount == 0:
            cursor.close()
            return HttpResponse(dumps({"code": general_utils.NOT_FOUND, "response": "forum not found"}))
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": general_utils.UNKNOWN_ERR, "response": unicode(db_err)}))
    forumId = cursor.fetchone()[0]

    all_forum_threads_query = SELECT_ALL_THREADS_BY_FORUM
    params = [forumId]
    since_date = general_utils.validate_date(request.GET.get("since"))
    if since_date:
        all_forum_threads_query += """AND date >= %s """
        params.append(since_date)
    elif since_date == False and since_date is not None:
        cursor.close()
        return HttpResponse(dumps({"code": general_utils.INCORRECT_QUERY, "response": "incorrect since_date fromat"}))

    order = request.GET.get("order", "desc")
    if order.lower() not in ("asc", "desc"):
        cursor.close()
        return HttpResponse(
            dumps({"code": general_utils.INCORRECT_QUERY, "response": "incorrect order parameter: {}".format(order)})
        )

    all_forum_threads_query += """ORDER BY thread.date """ + order

    limit = request.GET.get("limit")
    if limit:
        try:
            limit = int(limit)
        except ValueError:
            cursor.close()
            return HttpResponse(dumps({"code": general_utils.INCORRECT_QUERY, "response": "limit should be int"}))
        all_forum_threads_query += """ LIMIT %s"""
        params.append(limit)

    try:
        threads_qs = cursor.execute(all_forum_threads_query, params)
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": general_utils.UNKNOWN_ERR, "response": unicode(db_err)}))

    related = set(request.GET.getlist("related"))
    threads = []
    related_itemfunctions_dict = {"user": get_user_by_id, "forum": get_forum_by_id}
    for thread_item in cursor.fetchall():
        threads.append(
            {
                "date": thread_item[0].strftime("%Y-%m-%d %H:%M:%S"),
                "dislikes": thread_item[1],
                "forum": thread_item[2],
                "id": thread_item[3],
                "isClosed": thread_item[4],
                "isDeleted": thread_item[5],
                "likes": thread_item[6],
                "message": thread_item[7],
                "points": thread_item[8],
                "posts": thread_item[9],
                "slug": thread_item[10],
                "title": thread_item[11],
                "user": thread_item[12],
            }
        )

        related_itemids = {"forum": thread_item[13], "user": thread_item[14]}
        if "user" in related:
            get_related_iteminfo_func = related_itemfunctions_dict["user"]
            threads[-1]["user"], related_itemids_ = get_related_iteminfo_func(cursor, related_itemids["user"])
        else:
            cursor.close()
            return HttpResponse(
                dumps({"code": general_utils.INCORRECT_QUERY, "response": "incorrect related parameter"})
            )
        if "forum" in related:
            get_related_iteminfo_func = related_itemfunctions_dict["forum"]
            threads[-1]["forum"], related_itemids_ = get_related_iteminfo_func(cursor, related_itemids["forum"])
        else:
            cursor.close()
            return HttpResponse(
                dumps({"code": general_utils.INCORRECT_QUERY, "response": "incorrect related parameter"})
            )

    cursor.close()
    return HttpResponse(dumps({"code": general_utils.OK, "response": threads}))
Esempio n. 8
0
def create(request):
    cursor = connection.cursor()
    try:
        json_request = loads(request.body)
    except ValueError as value_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": unicode(value_err)}))

    try:
        message = json_request["message"]
        title = json_request["title"]
        is_closed = json_request["isClosed"]
        forum = json_request["forum"]
        date = json_request["date"]
        email = json_request["user"]
        slug = json_request["slug"]
    except KeyError as key_err:
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "Not found: {}".format(unicode(key_err))})
        )

    try:
        cursor.execute(SELECT_USER_BY_EMAIL, [email])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

    if cursor.rowcount == 0:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "user not found"}))
    userId = cursor.fetchone()[0]

    # forum validate
    try:
        cursor.execute(SELECT_FORUM_BY_SHORT_NAME, [forum])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))

    if cursor.rowcount == 0:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "forum not found"}))
    forumId = cursor.fetchone()[0]

    # message validate
    if not message:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "message should not be empty"}))

    # date validate
    date = general_utils.validate_date(date)
    if not date:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect date fromat"}))

    # validate slug
    if not title:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "title should not be empty"}))

    # slug validate
    if not slug:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "slug should not be empty"}))

    # validate is_closed
    is_closed = bool(is_closed)
    try:
        cursor.execute(INSERT_THREAD, [forumId, title, is_closed, userId, date, message, slug])
        cursor.execute(SELECT_LAST_INSERT_ID, [])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    threadId = cursor.fetchone()[0]

    is_deleted = json_request.get("isDeleted")
    if is_deleted is not None:
        is_deleted = bool(is_deleted)
        try:
            cursor.execute(UPDATE_THREAD_SET_DELETE_FLAG, [is_deleted, threadId])
        except DatabaseError as db_err:
            cursor.close()
            return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    else:
        is_deleted = False
    cursor.close()
    return HttpResponse(
        dumps(
            {
                "code": codes.OK,
                "response": {
                    "date": date,
                    "forum": forum,
                    "id": threadId,
                    "isClosed": is_closed,
                    "isDeleted": is_deleted,
                    "message": message,
                    "slug": slug,
                    "title": title,
                    "user": email,
                },
            }
        )
    )
Esempio n. 9
0
def listPosts(request):
    cursor = connection.cursor()
    if request.method != "GET":
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "request method should be GET"}))
    thread = request.GET.get("thread")
    threadId = general_utils.validate_id(thread)
    if threadId is None:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "thread id is required"}))
    if threadId == False:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "thread id should be int"}))
    try:
        cursor.execute(SELECT_THREAD_BY_ID, [threadId])
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    if cursor.rowcount == 0:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "thread was not found"}))
    threadId = cursor.fetchone()[0]

    all_posts_query = SELECT_ALL_POSTS_BY_THREAD
    query_params = [threadId]
    since_date = general_utils.validate_date(request.GET.get("since"))
    if since_date:
        all_posts_query += """AND post.date >= %s """
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect since_date fromat"}))

    order = request.GET.get("order", "desc")
    if order.lower() not in ("asc", "desc"):
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect order parameter: {}".format(order)})
        )

    posts_query_postfix = """ ORDER BY post.{} """ + order

    sort = request.GET.get("sort", "flat")
    if sort.lower() not in ("flat", "tree", "parent_tree"):
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect sort parameter: {}".format(sort)})
        )

    if sort == "flat":
        posts_query_postfix = posts_query_postfix.format("date")
    else:
        posts_query_postfix = posts_query_postfix.format("hierarchy_id")

    limit = request.GET.get("limit")
    if limit:
        try:
            limit = int(limit)
        except ValueError:
            cursor.close()
            return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "limit should be int"}))
        if sort == "flat" or sort == "tree":
            all_posts_query += posts_query_postfix + """ LIMIT %s"""
            query_params.append(limit)
        else:
            if order == "asc":
                operation = "<="
            else:
                operation = ">="
                try:
                    cursor.execute(SELECT_TOP_POST_NUMBER, [threadId])
                except DatabaseError as db_err:
                    cursor.close()
                    return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
                if cursor.rowcount:
                    max_posts_number = cursor.fetchone()[0]
                else:
                    max_posts_number = 0
                limit = max_posts_number - limit + 1
                if limit < 1:
                    limit = 1
            all_posts_query += "AND post.hierarchy_id {} '{}' ".format(operation, limit) + posts_query_postfix
    else:
        all_posts_query += posts_query_postfix

    try:
        cursor.execute(all_posts_query, query_params)
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    posts = []
    for post in cursor.fetchall():
        posts.append(
            {
                "date": post[0].strftime("%Y-%m-%d %H:%M:%S"),
                "dislikes": post[1],
                "forum": post[2],
                "id": post[3],
                "isApproved": not not post[4],
                "isDeleted": not not post[5],
                "isEdited": not not post[6],
                "isHighlighted": not not post[7],
                "isSpam": post[8],
                "likes": post[9],
                "message": post[10],
                "parent": post[11],
                "points": post[12],
                "thread": post[13],
                "user": post[14],
            }
        )
    cursor.close()
    return HttpResponse(dumps({"code": codes.OK, "response": posts}))
Esempio n. 10
0
def create(request):
    __cursor = connection.cursor()
    try:
        json_request = loads(request.body) 
    except ValueError as value_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': unicode(value_err)}))
    
    try:
        forum = json_request['forum']
        title = json_request['title']
        is_closed = json_request['isClosed']
        email = json_request['user']
        date = json_request['date']
        message = json_request['message']
        slug = json_request['slug']
    except KeyError as key_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'Not found: {}'.format(unicode(key_err))}))    
   
    # validate user
    try:
        user_id_qs = __cursor.execute(SELECT_USER_BY_EMAIL, [email, ])  
    except DatabaseError as db_err:
        __cursor.close() 
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))

    if not __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'user not found'}))
    user_id = __cursor.fetchone()[0]
    
    # validate forum
    try:
        __cursor.execute(SELECT_FORUM_BY_SHORT_NAME, [forum, ])  
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))

    if not __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'forum not found'}))
    forum_id = __cursor.fetchone()[0]
    #validate date
    date = general_utils.validate_date(date)
    if not date:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect date fromat'}))
    #validate message
    if not message:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'message should not be empty'}))

    #validate slug
    if not slug:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'slug should not be empty'}))
    #validate slug
    if not title:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'title should not be empty'}))

    #validate is_closed
    is_closed = bool(is_closed)
    try:
        __cursor.execute(INSERT_THREAD, [forum_id, title, is_closed, 
                                         user_id, date, message, slug])
        __cursor.execute(SELECT_LAST_INSERT_ID, [])
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)})) 
    thread_id = __cursor.fetchone()[0]

    is_deleted = json_request.get('isDeleted')
    if is_deleted is not None:
        is_deleted = bool(is_deleted)
        try:
            __cursor.execute(UPDATE_THREAD_SET_DELETE_FLAG, [is_deleted, thread_id])
        except DatabaseError as db_err: 
            __cursor.close()
            return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                       'response': unicode(db_err)})) 
    else:
        is_deleted = False       
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': {
                                   "date": date,
                                   "forum": forum,
                                    "id": thread_id,
                                    "isClosed": is_closed,
                                    "isDeleted": is_deleted,
                                    "message": message,
                                    "slug": slug,
                                    "title": title,
                                    "user": email
                                }}))
Esempio n. 11
0
def listThreads(request):
    __cursor = connection.cursor()
    if request.method != 'GET':
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'request method should be GET'}))
    short_name = request.GET.get('forum')
    if not short_name:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'forum name not found'})) 
    try:
        __cursor.execute(SELECT_FORUM_BY_SHORT_NAME, [short_name, ])
        if not __cursor.rowcount:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                        'response': 'forum not found'}))
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    forum_id = __cursor.fetchone()[0]

    get_all_forum_threads_specified_query = SELECT_ALL_THREADS_BY_FORUM
    query_params = [forum_id, ]
    since_date = general_utils.validate_date(request.GET.get('since'))
    if since_date:
        get_all_forum_threads_specified_query += '''AND date >= %s '''
        query_params.append(since_date)
    elif since_date == False and since_date is not None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect since_date fromat'}))
 
    order = request.GET.get('order', 'desc')
    if order.lower() not in ('asc', 'desc'):
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect order parameter: {}'.format(order)}))
    
    get_all_forum_threads_specified_query += '''ORDER BY thread.date ''' + order

    limit = request.GET.get('limit')
    if limit:
        try:
            limit = int(limit)
        except ValueError:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                        'response': 'limit should be int'}))
        get_all_forum_threads_specified_query += ''' LIMIT %s'''
        query_params.append(limit)

    try:
        threads_qs = __cursor.execute(get_all_forum_threads_specified_query, query_params) 
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)})) 
    
    related = set(request.GET.getlist('related'))
    threads = []
    related_functions_dict = {'user': get_user_by_id,
                              'forum': get_forum_by_id,
                              } 
    for thread in __cursor.fetchall():
        threads.append({
            "date": thread[0].strftime("%Y-%m-%d %H:%M:%S"),
            "dislikes": thread[1],
            "forum": thread[2],
            "id": thread[3],
            "isClosed": thread[4],
            "isDeleted": thread[5],
            "likes": thread[6],
            "message": thread[7],
            "points": thread[8],
            "posts": thread[9], 
            "slug": thread[10],
            "title": thread[11],
            "user": thread[12]
            })

        related_ids = {'forum': thread[13],
                       'user': thread[14]
                       }

        for related_ in  related:
            if related_ in ['user', 'forum']:
                get_related_info_func = related_functions_dict[related_]
                threads[-1][related_], related_ids_ = get_related_info_func(__cursor, related_ids[related_])  
            else:
                __cursor.close()
                return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                           'response': 'incorrect related parameter'}))     
    __cursor.close()        
    return HttpResponse(dumps({'code': codes.OK,
                               'response': threads
                               }))
Esempio n. 12
0
def create(request):
  try:
    __cursor = connection.cursor()
    try:
        json_request = loads(request.body) 
    except ValueError as value_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': unicode(value_err)}))
    
    try:
        date = json_request['date']
        thread_id = json_request['thread']
        message = json_request['message']
        forum = json_request['forum']
        email = json_request['user']
    except KeyError as key_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'Not found: {}'.format(unicode(key_err))}))    
    # validate user
    try:
        __cursor.execute(SELECT_USER_BY_EMAIL, [email, ])  
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))

    if not __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'user not found'}))
    user_id = __cursor.fetchone()[0]
    
    # validate forum
    try:
        __cursor.execute(SELECT_FORUM_BY_SHORT_NAME, [forum, ])  
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    if not __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'forum not found'}))
    forum_id = __cursor.fetchone()[0]

    try:
        __cursor.execute(INSERT_USER_TO_FORUM, [forum_id, user_id])
    except DatabaseError as db_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    #validate thread
    try:
        __cursor.execute(SELECT_THREAD_BY_ID, [thread_id, ])  
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    if not __cursor.rowcount:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'thread not found'}))
    thread_id = __cursor.fetchone()[0]
    
    #validate date
    date = general_utils.validate_date(date)
    if not date:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect date fromat'}))
    #validate message
    if not message:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'message should not be empty'}))

    #validate optional args
    query_params = [] 
    optional_args = ['isApproved', 'isDeleted', 'isEdited', 'isHighlighted', 'isSpam']
    for optional_arg_name in optional_args:
       optional_arg_value = json_request.get(optional_arg_name)
       if optional_arg_value is not None:
           #print optional_arg_name, optional_arg_value
           if not isinstance(optional_arg_value, bool):
               __cursor.close()
               return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                          'response': 'optional flag should be bool'})) 
           query_params.append([optional_arg_name, optional_arg_value])

    parent_id = json_request.get('parent')
    #print 'PARENT ID: ', parent_id
    with transaction.atomic():
        if parent_id:
            try:
                __cursor.execute(SELECT_PARENT_POST_HIERARCHY, [parent_id, ]) 
                if not __cursor.rowcount:
                     __cursor.close()
                     return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                                'response': 'parent post not found'})) 
                post = __cursor.fetchone()                
                __cursor.execute(UPDATE_CHILD_POST_COUNT, [parent_id, ])
            except DatabaseError as db_err: 
                __cursor.close()
                return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                           'response': unicode(db_err)}))

            hierarchy_id = post[2] + unicode(post[1] + 1) + '/'    
        else:
            try:
                __cursor.execute(SELECT_TOP_POST_NUMBER, [thread_id, ])
                if not __cursor.rowcount:
                     __cursor.execute(INSERT_TOP_POST_NUMBER, [thread_id,])
                     post_number = 1
                else:
                     post_number = __cursor.fetchone()[0] + 1
                     __cursor.execute(UPDATE_POST_NUMBER, [thread_id,])
            except DatabaseError as db_err: 
                __cursor.close()
                return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                           'response': unicode(db_err)}))
            hierarchy_id = unicode(post_number) + '/'
            
        try:
            post_qs = __cursor.execute(INSERT_POST, [hierarchy_id, date, message,
                                                     user_id, forum_id, thread_id, parent_id])
            __cursor.execute(SELECT_LAST_INSERT_ID, [])
        except DatabaseError as db_err: 
            __cursor.close()
            return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                       'response': unicode(db_err)})) 
        post_id = __cursor.fetchone()[0]

    update_post_query = UPDATE_POST_PREFIX
    if query_params:
        update_post_query += ", ".join([query_param[0] + '= %s' for query_param in query_params]) + \
                             ''' WHERE id = %s'''
        try:
            __cursor.execute(update_post_query, [query_param[1] for query_param in query_params] + [post_id,])
        except DatabaseError as db_err: 
            __cursor.close()
            return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                       'response': unicode(db_err)}))        

    try:
         post, realted_ids = get_post_by_id(__cursor, post_id)
    except TypeError:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': post}))
    if not post['isDeleted']:
        update_thread_posts(__cursor, thread_id, 1)
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': post}))
  except Exception as e:
    print e