Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit code repetition in app/views.py #441

Merged
merged 4 commits into from
Mar 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 71 additions & 117 deletions src/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login ,logout,update_session_auth_hash
from django.conf import settings
from django import forms
from django.template import RequestContext, context
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.models import User
from django.utils.datastructures import MultiValueDictKeyError
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from src.version import spdx_online_tools_version
Expand All @@ -33,15 +30,13 @@
import jpype
import requests
from lxml import etree
import re
import os
import logging
import json
from traceback import format_exc
from json import dumps, loads
from json import dumps
from time import time
from urllib.parse import urljoin
import xml.etree.cElementTree as ET
import datetime
import uuid
from wsgiref.util import FileWrapper
Expand All @@ -63,7 +58,6 @@
from .models import LicenseRequest, LicenseNamespace
from spdx_license_matcher.utils import get_spdx_license_text

import cgi

def index(request):
""" View for index
Expand Down Expand Up @@ -857,59 +851,47 @@ def license_xml_edit(request, page_id):
else:
return HttpResponseRedirect('/app/xml_upload')


def get_context_dict_for_license_xml(request, license_obj):
context_dict = {}
if request.user.is_authenticated:
user = request.user
try:
github_login = user.social_auth.get(provider="github")
except UserSocialAuth.DoesNotExist:
github_login = None
context_dict["github_login"] = github_login
context_dict["xml_text"] = license_obj.xml
context_dict["license_name"] = license_obj.fullname
return context_dict


def edit_license_xml(request, license_id=None):
"""View for editing the XML file corresponsing to a license entry
returns editor.html """
context_dict = {}
ajaxdict = {}
returns editor.html"""
if license_id:
if not LicenseRequest.objects.filter(id=license_id).exists():
return render(request,
'404.html',context_dict,status=404
)
if request.user.is_authenticated:
user = request.user
try:
github_login = user.social_auth.get(provider='github')
except UserSocialAuth.DoesNotExist:
github_login = None
context_dict["github_login"] = github_login
return render(request, "404.html", {}, status=404)
license_obj = LicenseRequest.objects.get(id=license_id)
context_dict["xml_text"] = license_obj.xml
context_dict["license_name"] = license_obj.fullname
return render(request,
'app/editor.html',context_dict,status=200
)
context_dict = get_context_dict_for_license_xml(request, license_obj)
return render(request, "app/editor.html", context_dict, status=200)
else:
return HttpResponseRedirect('/app/license_requests')


def edit_license_namespace_xml(request, license_id=None):
"""View for editing the XML file corresponsing to a license namespace entry
returns editor.html """
context_dict = {}
ajaxdict = {}
returns editor.html"""
if license_id:
if not LicenseNamespace.objects.filter(id=license_id).exists():
return render(request,
'404.html',context_dict,status=404
)
if request.user.is_authenticated:
user = request.user
try:
github_login = user.social_auth.get(provider='github')
except UserSocialAuth.DoesNotExist:
github_login = None
context_dict["github_login"] = github_login
return render(request, "404.html", {}, status=404)
license_obj = LicenseNamespace.objects.get(id=license_id)
context_dict["xml_text"] = license_obj.xml
context_dict["license_name"] = license_obj.fullname
return render(request,
'app/ns_editor.html',context_dict,status=200
)
context_dict = get_context_dict_for_license_xml(request, license_obj)
return render(request, "app/ns_editor.html", context_dict, status=200)
else:
return HttpResponseRedirect('/app/license_namespace_requests')


def archiveRequests(request, license_id=None):
""" View for archive license requests
returns archive_requests.html template
Expand Down Expand Up @@ -1205,112 +1187,84 @@ def issue(request):
return HttpResponseRedirect(settings.LOGIN_URL)


def pull_request(request):
""" View that handles pull request """
def handle_pull_request(request, is_ns):
"""Handler for pull request"""
if request.user.is_authenticated:
if request.method=="POST":
context_dict = {}
if request.method == "POST":
ajaxdict = {}
try:
if request.user.is_authenticated:
user = request.user
try:
""" Getting user info and calling the makePullRequest function """
github_login = user.social_auth.get(provider='github')
"""Getting user info and calling the makePullRequest function"""
github_login = user.social_auth.get(provider="github")
token = github_login.extra_data["access_token"]
username = github_login.extra_data["login"]
response = utils.makePullRequest(username, token, request.POST["branchName"], request.POST["updateUpstream"], request.POST["fileName"], request.POST["commitMessage"], request.POST["prTitle"], request.POST["prBody"], request.POST["xmlText"], False)
if(response["type"]=="success"):
""" PR made successfully """
if (request.is_ajax()):
response = utils.makePullRequest(
username,
token,
request.POST["branchName"],
request.POST["updateUpstream"],
request.POST["fileName"],
request.POST["commitMessage"],
request.POST["prTitle"],
request.POST["prBody"],
request.POST["xmlText"],
is_ns,
)
if response["type"] == "success":
"""PR made successfully"""
if request.is_ajax():
ajaxdict["type"] = "success"
ajaxdict["data"] = response["pr_url"]
response = dumps(ajaxdict)
return HttpResponse(response,status=200)
return HttpResponse(response["pr_url"],status=200)
return HttpResponse(response, status=200)
return HttpResponse(response["pr_url"], status=200)
else:
""" Error while making PR """
if (request.is_ajax()):
"""Error while making PR"""
if request.is_ajax():
ajaxdict["type"] = "pr_error"
ajaxdict["data"] = response["message"]
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse(response["message"],status=500)
return HttpResponse(response, status=500)
return HttpResponse(response["message"], status=500)
except UserSocialAuth.DoesNotExist:
""" User not authenticated with GitHub """
if (request.is_ajax()):
"""User not authenticated with GitHub"""
if request.is_ajax():
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse(response, status=401)
return HttpResponse("Please login using GitHub to use this feature.",status=401)
except:
""" Other errors raised """
"""Other errors raised"""
logger.error(str(format_exc()))
if (request.is_ajax()):
if request.is_ajax():
ajaxdict["type"] = "error"
ajaxdict["data"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
ajaxdict["data"] = (
"Unexpected error, please email the SPDX technical workgroup that the following error has occurred: "
+ format_exc()
)
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse("Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc(), status=500)
return HttpResponse(response, status=500)
return HttpResponse(
"Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc(),
status=500,
)
else:
return HttpResponseRedirect(settings.HOME_URL)
else:
return HttpResponseRedirect(settings.LOGIN_URL)


def pull_request(request):
""" View that handles pull request """
return handle_pull_request(request, is_ns=False)


def namespace_pull_request(request):
""" View that handles pull request for a license namespace """
if request.user.is_authenticated:
HirumalPriyashan marked this conversation as resolved.
Show resolved Hide resolved
if request.method=="POST":
context_dict = {}
ajaxdict = {}
try:
if request.user.is_authenticated:
user = request.user
try:
""" Getting user info and calling the makePullRequest function """
github_login = user.social_auth.get(provider='github')
token = github_login.extra_data["access_token"]
username = github_login.extra_data["login"]
response = utils.makePullRequest(username, token, request.POST["branchName"], request.POST["updateUpstream"], request.POST["fileName"], request.POST["commitMessage"], request.POST["prTitle"], request.POST["prBody"], request.POST["xmlText"], True)
if(response["type"]=="success"):
""" PR made successfully """
if (request.is_ajax()):
ajaxdict["type"] = "success"
ajaxdict["data"] = response["pr_url"]
response = dumps(ajaxdict)
return HttpResponse(response,status=200)
return HttpResponse(response["pr_url"],status=200)
else:
""" Error while making PR """
if (request.is_ajax()):
ajaxdict["type"] = "pr_error"
ajaxdict["data"] = response["message"]
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse(response["message"],status=500)
except UserSocialAuth.DoesNotExist:
""" User not authenticated with GitHub """
if (request.is_ajax()):
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse("Please login using GitHub to use this feature.",status=401)
except:
""" Other errors raised """
logger.error(str(format_exc()))
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse("Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc(), status=500)
else:
return HttpResponseRedirect(settings.HOME_URL)
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return handle_pull_request(request, is_ns=True)


def loginuser(request):
Expand Down