Skip to content

Commit

Permalink
Merge branch 'feature/questions' into practice_app
Browse files Browse the repository at this point in the history
  • Loading branch information
simsekhebun committed May 20, 2022
2 parents 3b22555 + ce51b59 commit 22f8d9b
Show file tree
Hide file tree
Showing 11 changed files with 209 additions and 8 deletions.
3 changes: 2 additions & 1 deletion Practice App/api/templates/index/index.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% extends "main/base.html" %}

{% block title %}
<title>Homepage</title>
Homepage
{% endblock %}

{% block content %}
Expand All @@ -27,4 +27,5 @@ <h3>Please choose one of the following API's to try out.</h3>
<div><span><a href="{% url 'list_tags' %}" >List all of the tags.</a></span></div>
<div><span><a href="{% url 'delete_tag' %}" >Delete a tag.</a></span></div>
<div><span><a href="{% url 'add_tags' %}" >Add a tag.</a></span></div>
<div><span><a href="{% url 'questions_form_main' %}" >Get freshest unanswered Stackexchange questions</a></span></div>
{% endblock %}
13 changes: 13 additions & 0 deletions Practice App/api/templates/questions/questions.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{% extends "main/base.html" %}

{% block content %}
<h3>Here you can search for unanswered questions in Stackexchange. (with answer count=0).</h3>
<p>Enter the tag you want to search for.</p>
<p>If you don't have a specific topic in mind, type "all" to get all the unanswered questions.</p>
<p>Tip: If you want to get the reply in pure json format, extend the result url with ?format=json</p>
<form action="{% url 'questions_form_main' %}" method="post", enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Get questions">
</form>
{% endblock %}
3 changes: 3 additions & 0 deletions Practice App/api/templates/tag/tagform.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{% extends "main/base.html" %}

{% block content %}
<h3>Here you can search for ArtItems tagged with the given tag.</h3>
<p>Enter the tag you want to search for.</p>
<p>Tip: If you want to get the reply in pure json format, extend the result url with ?format=json</p>
<form action="{% url 'search_by_tag_form_main' %}" method="post", enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
Expand Down
5 changes: 3 additions & 2 deletions Practice App/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""

from django.urls import path, include
from .views import view_artitems, view_myusers, view_search_by_tag, view_TVSeries, view_tags
from .views import view_artitems, view_myusers, view_search_by_tag, view_TVSeries, view_tags, view_questions
from rest_framework.urlpatterns import format_suffix_patterns
from .views import view_TVSeries
from .views import view_commentAPI
Expand Down Expand Up @@ -35,7 +35,8 @@
path('api/v1/users/<int:id>/comment/<int:commentid>', view_commentAPI.getDeleteComment, name= "getDeleteComment"),
path('api/v1/tags/', view_tags.tags, name="tags"),
path('api/v1/tags/<int:id>', view_tags.delete_tag_byID, name="delete_tag_byID"),
path('api/v1/users/username/<str:username>', view_search_user.search_user, name="search_username")
path('api/v1/users/username/<str:username>', view_search_user.search_user, name="search_username"),
path('api/v1/questions/<str:tag>', view_questions.getquestions, name="getquestions"),
]

#added to give us the option to choose between default Response template and regular json
Expand Down
77 changes: 77 additions & 0 deletions Practice App/api/views/view_questions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from urllib import response
from django.shortcuts import render
import requests
import json
from django.http import HttpResponse, JsonResponse
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

# this view uses the stackexchange api (given below) to get unanswered questions (with answercount 0) and depending on the given keyword tag
#either returns all the unanswered questions if tag == "all"
# or returns unanswered questions tagged with the given tag
#the Response uses default django html template, extend the url with <?format=json> to get pure json


@api_view(['GET'])
def getquestions(request, tag, format=None ):
response = requests.get('http://api.stackexchange.com/2.3/questions/unanswered?order=desc&sort=activity&site=stackoverflow')

unansweredquestions = {}
#unansweredquestions['allquestions']=[]
allquestions = []

if tag == "all":
for question in response.json()['items']:
if question['answer_count']==0 :
questiondata = {}
questiondata['title'] = question['title']
questiondata['link'] = question['link']
questiondata['tags'] = question['tags']
allquestions.append(questiondata)

#print(question['title'])
#print(question['link'])
#else:
# print("skipped")
#print()

if allquestions == []:
unansweredquestions["message"] = "Sorry there are no unanswered questions at the moment, please try again later."
return Response(unansweredquestions, status= status.HTTP_404_NOT_FOUND)

unansweredquestions['allquestions']= allquestions

#return JsonResponse(unansweredquestions)
return Response(unansweredquestions, status= status.HTTP_200_OK)

if response.json() == {}:
#print(response.json())
unansweredquestions["message"] = "Sorry there are no unanswered questions with the given tag at the moment, please try again later."
return Response(unansweredquestions, status= status.HTTP_404_NOT_FOUND)



for question in response.json()['items']:
if question['answer_count']==0 and tag in question['tags']: #and "shell" in question['tags']
questiondata = {}
questiondata['title'] = question['title']
questiondata['link'] = question['link']
questiondata['tags'] = question['tags']
allquestions.append(questiondata)

#print(question['title'])
#print(question['link'])
#else:
# print("skipped")
#print()

if allquestions == []:
unansweredquestions["message"] = "Sorry there are no unanswered questions with the given tag at the moment, please try again later."
return Response(unansweredquestions, status= status.HTTP_404_NOT_FOUND)

unansweredquestions['allquestions']= allquestions

#return JsonResponse(unansweredquestions)
return Response(unansweredquestions, status= status.HTTP_200_OK)
#return HttpResponse("Bravo!")
8 changes: 7 additions & 1 deletion Practice App/api/views/view_search_by_tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,17 @@ def search_by_tag(request, tag, format=None):
try:
tagObject = Tag.objects.get(tagname=tag)
except Tag.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
resp = {}
resp["message"]= "Sorry, the given tag does not exist. Perhaps try get all tags API to see what tags are available."
return Response(resp, status=status.HTTP_404_NOT_FOUND)


if request.method == 'GET':
items= tagObject.artitem_set.all()
# items = ArtItem.objects.all()
serializer = ArtItemSerializer(items, many=True)
if serializer.data == []:
resp = {}
resp["message"]= "Sorry, currently there are no art items tagged with the given tag. Perhaps try get all art items API to see what art items are available."
return Response(resp, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.data, status=status.HTTP_200_OK)
5 changes: 4 additions & 1 deletion Practice App/django_app/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from django import forms

class TagForm(forms.Form):
tag=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter tag name'}), max_length=100)
tag=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter tag name'}), max_length=100)

class QuestionTagForm(forms.Form):
tag=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Question tag'}), max_length=100)
3 changes: 2 additions & 1 deletion Practice App/django_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,6 @@
path('user/id/comment/commentid', views.deleteComment, name= "deleteComment"),
path('tag/id', views.delete_tag, name="delete_tag"),
path('tag/new', views.add_tags, name="add_tags"),
path('search_user/',views.search_user ,name="search_user")
path('search_user/',views.search_user ,name="search_user"),
path('questions/form', views.questions, name="questions_form_main"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
19 changes: 18 additions & 1 deletion Practice App/django_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import redirect, render
from .forms import TagForm
from .forms import TagForm, QuestionTagForm
import urllib.parse
import requests
import json
Expand Down Expand Up @@ -107,3 +107,20 @@ def delete_user_by_id(request):
def search_user(request):
return render(request,'search_user/searchuser.html')

def questions(request):
if request.POST:
form = QuestionTagForm(request.POST)
print(request.POST)
tag=request.POST["tag"]
#print("here")
#print(tag)
if form.is_valid():
#encoded = urllib.parse.quote(str(tag))
#print(encoded)
#print(encoded)
return redirect('getquestions', tag=tag) #Redirect to search_by_tag page
#response = request.get('http://127.0.0.1:8000/api/searchbytag/{encoded}')


return render(request, 'questions/questions.html', {'form':QuestionTagForm()}) #import render
#return HttpResponse("why though")
60 changes: 60 additions & 0 deletions Practice App/tests/test_questions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from urllib import response
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.test import TestCase, Client
from api.serializers import myUserSerializer, ArtItemSerializer, CommentSerializer, TagSerializer
from api.models import ArtItem, Tag, myUser
from django.contrib.auth.models import User
import json
from faker import Faker

class TestQuestions(APITestCase):

def setUp(self):
# setting up for the test
print("TestQuestions:setUp_:begin")

##### Mock up data #####

faker = Faker()
self.tagname = faker.word()

print("TestQuestions:setUp_:end")



def tearDown(self):
# cleaning up after the test
print("TestQuestions:setUp_:begin")

# do something
print("TestQuestions:setUp_:end")


def test_questions_all(self):
response = self.client.get('/api/v1/questions/all')
unansweredquestions = {}
unansweredquestions["message"] = "Sorry there are no unanswered questions at the moment, please try again later."

if response.status_code == 404:
self.assertEqual(response.json(), unansweredquestions ) # check if the error message is correct

else:
self.assertEqual(response.status_code, 200 )
self.assertNotEqual(response.json(), {})
self.assertNotEqual(response.json(), unansweredquestions)

def test_questions_tag(self):
response = self.client.get('/api/v1/questions/{}'.format(self.tagname))
unansweredquestions = {}
unansweredquestions["message"] = "Sorry there are no unanswered questions with the given tag at the moment, please try again later."

if response.status_code == 404:
self.assertEqual(response.json(), unansweredquestions ) # check if the error message is correct

else:
self.assertEqual(response.status_code, 200 )
self.assertNotEqual(response.json(), {})
self.assertNotEqual(response.json(), unansweredquestions)

21 changes: 20 additions & 1 deletion Practice App/tests/test_searchbtg.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ def setUp(self):
self.artitemId = test_artitem.id
test_artitem.tags.add(test_tag)

self.tagname2 = 'someweirdwordtnottobeusedelsewhere'
test_tag2 = Tag.objects.create(tagname = self.tagname2, description = faker.paragraph(nb_sentences=3))

print("TestSearchbtg:setUp_:end")

Expand All @@ -50,7 +52,24 @@ def test_get_tagged_artitems(self):
expected = serializer.data
self.assertEqual(response.json(), expected)


def test_get_tagged_artitems_no_tag(self):
response = self.client.get('/api/v1/searchbytag/someweirdname')
self.assertEqual(response.status_code, 404) # check status code
resp = {}
resp["message"]= "Sorry, the given tag does not exist. Perhaps try get all tags API to see what tags are available."
self.assertEqual(response.json(), resp)

def test_get_tagged_artitems_no_item_with_tag(self):
response = self.client.get('/api/v1/searchbytag/{}'.format(self.tagname2))
self.assertEqual(response.status_code, 204) # check status code
resp = {}
resp["message"]= "Sorry, currently there are no art items tagged with the given tag. Perhaps try get all art items API to see what art items are available."
#print("Response:")
#print(response.data)
#print(response.json())
#print("Resp:")
#print(resp)
self.assertEqual(response.data, resp)



0 comments on commit 22f8d9b

Please sign in to comment.