Exemplo n.º 1
0
def update(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:
        postId = json_request["post"]
        message = unicode(json_request["message"])
    except KeyError as key_err:
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "Not found: {}".format(unicode(key_err))})
        )

    postId = codes_and_utils.validate_id(postId)
    if postId == False:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "post id should be int"}))
    try:
        cursor.execute(SELECT_POST_BY_ID, [postId])
        if cursor.rowcount == 0:
            cursor.close()
            return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "post not found"}))
        postId_qs = cursor.execute(UPDATE_POST_MESSAGE, [message, postId])
        post, related_obj = get_post_by_id(cursor, postId)
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    cursor.close()
    return HttpResponse(dumps({"code": codes.OK, "response": post}))
Exemplo n.º 2
0
def details(request):
    cursor = connection.cursor()
    if request.method != "GET":
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "request method should be GET"}))
    postId = codes_and_utils.validate_id(request.GET.get("post"))
    if postId is None:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "post id not found"}))
    if postId == False:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "post id should be int"}))
    try:
        post, related_ids = get_post_by_id(cursor, postId)
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    except TypeError:
        cursor.close()
        return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "post not found"}))
    related = request.GET.getlist("related")
    related_functions_dict = {"user": get_user_by_id, "thread": get_thread_by_id, "forum": get_forum_by_id}
    for related_ in related:
        if related_ in ["user", "forum", "thread"]:
            get_related_info_func = related_functions_dict[related_]
            post[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": post}))
Exemplo n.º 3
0
Arquivo: vote.py Projeto: niggor/apiDB
def vote(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:
        post_id = json_request['post']
        vote_ = json_request['vote']
    except KeyError as key_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'Not found: {}'.format(unicode(key_err))}))

    post_id = general_utils.validate_id(post_id) 
    if post_id == False:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'post id should be int'}))
    try:
        vote_ = int(vote_)
        if abs(vote_) != 1:
            raise ValueError
    except ValueError:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'incorrect vote value'})) 
    if vote_ < 0:
        column_name = 'dislikes'
    else:
        column_name = 'likes'
  
    try:
        __cursor.execute(SELECT_POST_BY_ID, [post_id, ])
        if not __cursor.rowcount:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                        'response': 'post not found'})) 
        __cursor.execute(UPDATE_POST_VOTES.format(column_name, column_name), [post_id, ]) 
        if not __cursor.rowcount:
            __cursor.close()
            return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                        'response': 'post not found'}))
        post, related_obj = get_post_by_id(__cursor, post_id)
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))     
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': post}))
Exemplo n.º 4
0
def vote(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:
        postId = json_request["post"]
        vote = json_request["vote"]
    except KeyError as key_err:
        cursor.close()
        return HttpResponse(
            dumps({"code": codes.INCORRECT_QUERY, "response": "Not found: {}".format(unicode(key_err))})
        )

    postId = codes_and_utils.validate_id(postId)
    if postId == False:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INVALID_QUERY, "response": "post id should be int"}))
    vote = int(vote)
    if abs(vote) != 1:
        cursor.close()
        return HttpResponse(dumps({"code": codes.INCORRECT_QUERY, "response": "incorrect vote value"}))

    if vote < 0:
        column_name = "dislikes"
    else:
        column_name = "likes"

    try:
        cursor.execute(SELECT_POST_BY_ID, [postId])
        if cursor.rowcount == 0:
            cursor.close()
            return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "post not found"}))
        cursor.execute(UPDATE_POST_VOTES.format(column_name, column_name), [postId])
        if cursor.rowcount == 0:
            cursor.close()
            return HttpResponse(dumps({"code": codes.NOT_FOUND, "response": "post not found"}))
        post, related_obj = get_post_by_id(cursor, postId)
    except DatabaseError as db_err:
        cursor.close()
        return HttpResponse(dumps({"code": codes.UNKNOWN_ERR, "response": unicode(db_err)}))
    cursor.close()
    return HttpResponse(dumps({"code": codes.OK, "response": post}))
Exemplo n.º 5
0
def details(request):
    __cursor = connection.cursor()
    if request.method != 'GET':
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'request method should be GET'}))
    post_id = general_utils.validate_id(request.GET.get('post'))
    if post_id is None:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'post id not found'})) 
    if post_id == False:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'post id should be int'})) 
    try:
        post, related_ids = get_post_by_id(__cursor, post_id) 
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)}))
    except TypeError:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                   'response': 'post not found'}))
    related = request.GET.getlist('related')
    related_functions_dict = {
                          'user': get_user_by_id,
                          'thread': get_thread_by_id,
                          'forum': get_forum_by_id
                          }
    for related_ in related:
        if related_ in ['user', 'forum', 'thread']:
            get_related_info_func = related_functions_dict[related_]
            post[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': post}))
Exemplo n.º 6
0
def update(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:
        post_id = json_request['post']
        message = unicode(json_request['message'])
    except KeyError as key_err:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INCORRECT_QUERY,
                                   'response': 'Not found: {}'.format(unicode(key_err))}))

    post_id = general_utils.validate_id(post_id) 
    if post_id == False:
        __cursor.close()
        return HttpResponse(dumps({'code': codes.INVALID_QUERY,
                                   'response': 'post id should be int'})) 
    try:
        __cursor.execute(SELECT_POST_BY_ID, [post_id, ])
        if not __cursor.rowcount:
             __cursor.close()
             return HttpResponse(dumps({'code': codes.NOT_FOUND,
                                        'response': 'post not found'})) 
        post_id_qs = __cursor.execute(UPDATE_POST_MESSAGE, [message, post_id]) 
        post, related_obj = get_post_by_id(__cursor, post_id)
    except DatabaseError as db_err: 
        __cursor.close()
        return HttpResponse(dumps({'code': codes.UNKNOWN_ERR,
                                   'response': unicode(db_err)})) 
    __cursor.close()
    return HttpResponse(dumps({'code': codes.OK,
                               'response': post}))
Exemplo n.º 7
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}))
Exemplo n.º 8
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