Adding an api call and service for Contributors page

This commit is contained in:
Gowtham Sai 2022-11-02 18:49:00 +05:30
parent 0058feb06e
commit 28bdba2b17
7 changed files with 105 additions and 0 deletions

View File

@ -276,3 +276,16 @@ class PrePlacementOffer(models.Model):
self.changed_by = value
else:
self.changed_by = None
class Contributor(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=JNF_SMALLTEXT_MAX_CHARACTER_COUNT, blank=False, default="")
email = models.EmailField(max_length=JNF_SMALLTEXT_MAX_CHARACTER_COUNT, blank=False, default="", unique=True)
github_id = models.CharField(max_length=JNF_SMALLTEXT_MAX_CHARACTER_COUNT, blank=False, default="", unique=True)
linkedin = models.CharField(max_length=JNF_SMALLTEXT_MAX_CHARACTER_COUNT, unique=True, null=True)
commits = models.IntegerField(blank=False, default=0)
image = models.CharField(max_length=JNF_SMALLTEXT_MAX_CHARACTER_COUNT, blank=False, default="", null=True)
def __str__(self):
return self.name

View File

@ -185,3 +185,7 @@ class PlacementApplicationSerializerForAdmin(serializers.ModelSerializer):
class Meta:
model = PlacementApplication
exclude = ['placement', 'resume']
class ContributorSerializer(serializers.ModelSerializer):
class Meta:
model = Contributor

View File

@ -10,4 +10,5 @@ urlpatterns = [
path("deleteResume/", studentViews.deleteResume, name="Upload Resume"),
path("submitApplication/", studentViews.submitApplication, name="Submit Application"),
path("deleteApplication/", studentViews.deleteApplication, name="Delete Application"),
path("getContributorStats/", studentViews.getContributorStats, name="Get Contributor Stats"),
]

View File

@ -231,3 +231,19 @@ def deleteApplication(request, id, email, user_type):
return Response({'action': "Delete Application", 'message': "Something Went Wrong"},
status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
@isAuthorized(allowed_users='*')
def getContributorStats(request, id, email, user_type):
try:
contributors = Contributor.objects.all()
serialized_data = ContributorSerializer(contributors, many=True).data
return Response({'action': "Get Contributor Stats", 'message': "Contributor Stats Fetched",
'data': serialized_data},
status=status.HTTP_200_OK)
except:
logger.warning("Get Contributor Stats: " + str(sys.exc_info()))
return Response({'action': "Get Contributor Stats", 'message': "Something Went Wrong"},
status=status.HTTP_400_BAD_REQUEST)

View File

@ -46,6 +46,7 @@ INSTALLED_APPS = [
'background_task',
'simple_history',
'import_export',
"django_extensions"
]
MIDDLEWARE = [

View File

View File

@ -0,0 +1,70 @@
from APIs.models import Contributor
from django.shortcuts import get_object_or_404
import time
from dotenv import load_dotenv
import requests
import os
load_dotenv("../dev.env")
owner = 'CDC-IITDH'
access_token = os.environ.get("GITHUB_ACCESS_TOKEN")
headers = {'Authorization': "Token " + access_token}
maxRetires = 10
REPEAT_AFTER = 60 * 15 # 15 minutes
def getStats():
try:
stats = {}
repos = ['cdc-placement-website-backend', 'cdc-placement-website-frontend']
for i in repos:
try:
repo_name = i
print(repo_name)
url = f"https://api.github.com/repos/{owner}/{repo_name}/stats/contributors"
retry = 0
contributors = []
while True:
if retry > maxRetires:
break
req = requests.get(url, headers=headers)
contributors = req.json()
if req.status_code != 200:
print("ERROR:", req.json())
retry += 1
elif len(contributors):
break
retry += 1
time.sleep(1)
for contributor in contributors:
if contributor['author']['login'] not in stats:
stats[contributor['author']['login']] = 0
stats[contributor['author']['login']] += contributor['total']
except Exception as e:
print(e)
for i in stats:
try:
contributor = get_object_or_404(Contributor, github_id=i)
contributor.commits = stats[i]
contributor.save()
except:
pass
stats = sorted(stats.items(), key=lambda x: x[1], reverse=True)
for i in stats:
print(i)
except Exception as e:
print(e)
return stats
def run():
while True:
getStats()
print("Sleeping for", REPEAT_AFTER, "seconds")
time.sleep(REPEAT_AFTER)
print("Running send_reminder_mails()")
run()