Exemplo n.º 1
0
def viewQuestion(request):
  #obtain question by ID
  questionId = request.GET["questionId"]
  q = Question(id=questionId)
  q = q.findById()
  # no increment when the query come from the ajax system  
  if not request.GET.__contains__("auto")  :
    q.views+=1
  q.update()
  
  #unwrap answer dictionaries so that we can serialize into json
  answerList = []
  for answer in q.answers:
    answerList.append(answer.unwrap())

  response = json.dumps({
    'id': q.id,
    'title': q.title,
    'description': q.description,
    'asker': q.asker,
    'views': q.views,
    'answers': answerList,
    'topics' : q.topics
  })
  return HttpResponse(response)
Exemplo n.º 2
0
def post(request):
    # get current user
    context = checkSession(request)
    user = getCurrentUser(context)

    # get question data
    questionTitle = smart_unicode(request.POST["title"], encoding="utf-8", strings_only=False, errors="strict")
    questionDescription = smart_unicode(
        request.POST["description"], encoding="utf-8", strings_only=False, errors="strict"
    )

    if not user:
        message = "you must be logged in first!"
    elif questionTitle == "":
        message = "a question needs words!"
    else:
        # create question
        q = Question(asker=user.login, title=questionTitle, description=questionDescription)
        if request.POST.__contains__("tags"):
            tags = smart_unicode(request.POST["tags"], encoding="utf-8", strings_only=False, errors="strict")
            topics = tags.split(",")
            q.topics = topics
        try:
            q.create()
        except Exception as e:
            message = e
        else:
            message = "question successfully posted"

    response = HttpResponse()
    response["message"] = message
    return response
Exemplo n.º 3
0
def getAnswersJson(questionId):
  q = Question(id=questionId)
  q = q.findById()
  answerList = []
  for answer in q.answers:
    answerList.append(answer.unwrap())
  return json.dumps(answerList)
Exemplo n.º 4
0
def rateAnswer(request):
  context=checkSession(request)
  user = getCurrentUser(context)
  questionId = request.POST["questionId"]
  
  if user is None:
    response=HttpResponse(getAnswersJson(questionId))
    response['errorMessage']='You must be logged in to rate an answer'
    return response
    
  
  ratingType = request.POST["type"]
  answerId = request.POST["answerId"]
  
  r=Rating(_id=sha1(user.id+answerId).hexdigest())  
  if r.findById() :
    response=HttpResponse(getAnswersJson(questionId))
    response['errorMessage']='You have already rated this answer'
    return response
  
  
  q = Question(id=questionId)
  q = q.findById()
  updated = False
  for answer in q.answers:
    if answer.id == answerId:
      if answer.score is None:
        answer.score =0
      if ratingType == 'increment':
        answer.score += 1
      else:
        answer.score -= 1
      q.update()
      updated = True

  errorMessage = ''
  if updated:
    r.create();
  else:
    errorMessage = 'could not update rating'

  #unwrap answer dictionaries so that we can serialize into json
  answerList = []
  for answer in q.answers:
    answerList.append(answer.unwrap())
  response = HttpResponse(json.dumps(answerList))
  response['errorMessage'] = errorMessage
  response['editedId'] = answerId
  return response
Exemplo n.º 5
0
def displayFollowedQuestions(request):
    context = checkSession(request)
    user = getCurrentUser(context)
    if user is None:
        return HttpResponse()

    user = user.findByLogin()

    questionList = []
    for questionId in user.followedQuestions:
        q = Question(id=questionId)
        q = q.findById()
        questionList.append({"id": q.id, "content": q.content})

    return HttpResponse(json.dumps(questionList))
Exemplo n.º 6
0
def postAnswer(request):
  context=checkSession(request)
  user = getCurrentUser(context)
  if user is None:
    return HttpResponse(json.dumps({'error':1, 'errorMessage': 'You need to be logged in to post an answer'}))

  #obtain question by ID
  questionId = request.POST["questionId"]
  q = Question(id=questionId)
  q = q.findById()

  #create answer ID by hashing (userId, questionId) 
  answerId = sha1(user.id + questionId).hexdigest()

  #check if answer ID already exists
  #this means that this user already posted an answer for this question -> abort post
  #the following is deactivated for development purposes
  for answer in q.answers:
    if answer.id == answerId:
      return HttpResponse(json.dumps({'error':1, 'errorMessage': 'You have already posted an answer for this Kuestion!'}))

  content = smart_unicode(request.POST["answer"], encoding='utf-8', strings_only=False, errors='strict')
  newAnswer = {'content': content, 'id': answerId, 'poster':user.login}
  q.answers.append(newAnswer)
  q.update()
  #time line event creation
  t=TimeLineEvent()
  t.user=user.login
  t.action="POST"
  t.questionTitle=Question(id=questionId).findById().title
  t.answer=answerId
  t.question=questionId
  t.create()

  print t
  
  
  print 'answer added to question: ' + str(q)

  #unwrap answer dictionaries so that we can serialize into json
  answerList = []
  for answer in q.answers:
    answerList.append(answer.unwrap())

  response = HttpResponse(json.dumps(answerList))
  response['lastAddedId'] = newAnswer['id']
  return response
Exemplo n.º 7
0
def displayFollowedQuestions(request):
    context = checkSession(request)
    user = getCurrentUser(context)
    if user is None:
        return HttpResponse()

    user = user.findByLogin()

    questionList = []
    for questionId in user.followedQuestions:
        q = Question(id=questionId)
        q = q.findById()
        questionList.append({
            'id': q.id,
            'content': q.content,
        })

    return HttpResponse(json.dumps(questionList))
Exemplo n.º 8
0
def postAnswer(request):
    # obtain question by ID
    questionId = request.POST["questionId"]
    q = Question(id=questionId)
    q = q.findById()

    # create answer ID by hashing (userId, questionId)
    context = checkSession(request)
    user = getCurrentUser(context)
    if user is None:
        return HttpResponse(json.dumps({"error": 1, "errorMessage": "You need to be logged in to post an answer"}))
    answerId = sha1(user.id + questionId).hexdigest()

    # check if answer ID already exists
    # this means that this user already posted an answer for this question -> abort post
    # the following is deactivated for development purposes
    """
  for answer in q.answers:
    if answer.id == answerId:
      return HttpResponse(json.dumps({'error':1, 'errorMessage': 'You have already posted an answer for this Kuestion!'}))
  """
    content = request.POST["answer"]
    newAnswer = {"content": content, "id": answerId, "poster": user.login}
    q.answers.append(newAnswer)
    q.update()
    # time line event creation
    t = TimeLineEvent()
    t.user = user.login
    t.action = "POST"
    t.questionTitle = Question(id=questionId).findById().content
    t.answer = answerId
    t.question = questionId
    t.create()

    print t

    print "answer added to question: " + str(q)

    # unwrap answer dictionaries so that we can serialize into json
    answerList = []
    for answer in q.answers:
        answerList.append(answer.unwrap())

    return HttpResponse(json.dumps(answerList))
Exemplo n.º 9
0
def displayFollowedQuestions(request):
  context = checkSession(request)
  user = getCurrentUser(context)
  if user is None:
    return HttpResponse()

  user = user.findByLogin()

  questionList = []
  for questionId in user.followedQuestions:
    q = Question(id=questionId)
    q = q.findById()
    questionList.append({
      'id': q.id,
      'title': q.title,
      'asker': q.asker,
      'postDate': q.postDate.isoformat(),
    })

  return HttpResponse(json.dumps(questionList))
Exemplo n.º 10
0
def post(request):
    #get current user
    context = checkSession(request)
    user = getCurrentUser(context)

    #get question data
    questionTitle = smart_unicode(request.POST["title"],
                                  encoding='utf-8',
                                  strings_only=False,
                                  errors='strict')
    questionDescription = smart_unicode(request.POST["description"],
                                        encoding='utf-8',
                                        strings_only=False,
                                        errors='strict')

    if not user:
        message = 'you must be logged in first!'
    elif questionTitle == "":
        message = 'a question needs words!'
    else:
        #create question
        q = Question(asker=user.login,
                     title=questionTitle,
                     description=questionDescription)
        if request.POST.__contains__("tags"):
            tags = smart_unicode(request.POST["tags"],
                                 encoding='utf-8',
                                 strings_only=False,
                                 errors='strict')
            topics = tags.split(',')
            q.topics = topics
        try:
            q.create()
        except Exception as e:
            message = e
        else:
            message = 'question successfully posted'

    response = HttpResponse()
    response["message"] = message
    return response
Exemplo n.º 11
0
def viewQuestion(request):
    # obtain question by ID
    questionId = request.GET["questionId"]
    q = Question.load(getDb(), questionId)

    # unwrap answer dictionaries so that we can serialize into json
    answerList = []
    for answer in q.answers:
        answerList.append(answer.unwrap())

    response = json.dumps({"id": q.id, "title": q.title, "asker": q.asker, "views": q.views, "answers": answerList})
    return HttpResponse(response)
Exemplo n.º 12
0
def post(request) :
  #get current user
  context = checkSession(request)
  user = getCurrentUser(context)

  #get question data
  questionTitle = smart_unicode(request.POST["title"], encoding='utf-8', strings_only=False, errors='strict')
  questionDescription = smart_unicode(request.POST["description"], encoding='utf-8', strings_only=False, errors='strict')

  if not user:
    message = 'you must be logged in first!'
  elif questionTitle == "":
    message = 'a question needs words!'
  else:
    #create question
    q = Question(asker=user.login, title=questionTitle, description=questionDescription)
    if request.POST.__contains__("tags") :
      tags=smart_unicode(request.POST["tags"], encoding='utf-8', strings_only=False, errors='strict')
      topics=tags.split(',')
      q.topics=topics
    print q
    try :
      q.create()
      q=q.findById()
      user=user.findByLogin()
      user.followedQuestions.append(q.id);
      user.update()
      message = 'question successfully posted'
    except Exception as e:
      message = e
  #remove the displayed question 
  response = HttpResponse();
  response["message"] = message;
  response["questionId"] = q.id;
  return response;
Exemplo n.º 13
0
def viewQuestion(request):
  #obtain question by ID
  questionId = request.GET["questionId"]
  q = Question(id=questionId)
  q = q.findById()
  if q.views is None :
    q.views = 0
  q.views+=1
  q.update()
  
  #unwrap answer dictionaries so that we can serialize into json
  answerList = []
  for answer in q.answers:
    answerList.append(answer.unwrap())

  response = json.dumps({
    'id': q.id,
    'title': q.title,
    'asker': q.asker,
    'views': q.views,
    'answers': answerList,
  })
  return HttpResponse(response)
Exemplo n.º 14
0
def viewQuestion(request):
    #obtain question by ID
    questionId = request.GET["questionId"]
    q = Question.load(getDb(), questionId)

    #unwrap answer dictionaries so that we can serialize into json
    answerList = []
    for answer in q.answers:
        answerList.append(answer.unwrap())

    response = json.dumps({
        'id': q.id,
        'title': q.title,
        'asker': q.asker,
        'views': q.views,
        'answers': answerList,
    })
    return HttpResponse(response)
Exemplo n.º 15
0
def postAnswer(request):
    #obtain question by ID
    questionId = request.POST["questionId"]
    q = Question(id=questionId)
    q = q.findById()

    #create answer ID by hashing (userId, questionId)
    context = checkSession(request)
    user = getCurrentUser(context)
    if user is None:
        return HttpResponse(
            json.dumps({
                'error':
                1,
                'errorMessage':
                'You need to be logged in to post an answer'
            }))
    answerId = sha1(user.id + questionId).hexdigest()

    #check if answer ID already exists
    #this means that this user already posted an answer for this question -> abort post
    #the following is deactivated for development purposes
    '''
  for answer in q.answers:
    if answer.id == answerId:
      return HttpResponse(json.dumps({'error':1, 'errorMessage': 'You have already posted an answer for this Kuestion!'}))
  '''
    content = request.POST["answer"]
    newAnswer = {'content': content, 'id': answerId, 'poster': user.login}
    q.answers.append(newAnswer)
    q.update()
    #time line event creation
    t = TimeLineEvent()
    t.user = user.login
    t.action = "POST"
    t.questionTitle = Question(id=questionId).findById().content
    t.answer = answerId
    t.question = questionId
    t.create()

    print t

    print 'answer added to question: ' + str(q)

    #unwrap answer dictionaries so that we can serialize into json
    answerList = []
    for answer in q.answers:
        answerList.append(answer.unwrap())

    return HttpResponse(json.dumps(answerList))
Exemplo n.º 16
0
def createQuestion(title):
  #get a random user as the asker
  userlist = getDb().view('user/login')
  randomAsker = random.choice( userlist.rows ).value['login']

  #add topics
  topics = title.replace('?','').lower().split(' ')
  #remove prepositions
  f = open('prepositions')
  prepositions = f.read().splitlines()
  f.close()

  for preposition in prepositions:
    topics = [e for e in topics if e != preposition]
  nontopics = [
    'some',
    'is',
    'the',
    'what',
    'when',
    'why',
    'how',
    'who',
    'where',
    'a',
    'this',
    'that',
    'are',
    'i',
    'you',
    'can',
    'do'
  ]
  for word in nontopics:
    topics = [e for e in topics if e != word]
  
  #convert title to unicode
  title = smart_unicode(title, encoding='utf-8', strings_only=False, errors='strict')

  #create question
  q = Question(asker=randomAsker, title=title, topics=topics)
  print '********** creating question ***********\n' + 'title: ' + title + '\nasker: ' + randomAsker + '\ntopics: ' + str(topics)
  q.create()
  q.update()
Exemplo n.º 17
0
def viewQuestion(request):
    #obtain question by ID
    questionId = request.GET["questionId"]
    q = Question(id=questionId)
    q = q.findById()
    if q.views is None:
        q.views = 0
    q.views += 1
    q.update()

    #unwrap answer dictionaries so that we can serialize into json
    answerList = []
    for answer in q.answers:
        answerList.append(answer.unwrap())

    response = json.dumps({
        'id': q.id,
        'title': q.title,
        'asker': q.asker,
        'views': q.views,
        'answers': answerList,
    })
    return HttpResponse(response)