From ed3cac2e6b94576c5c689c2b172a536ee6a6ac44 Mon Sep 17 00:00:00 2001 From: Varun Patil Date: Sun, 17 Mar 2024 15:19:07 -0700 Subject: [PATCH 1/2] chore: fix lint --- .flake8 | 2 +- locations/management/commands/mapnav.py | 53 ++++++++++++------------- locations/views.py | 8 ++-- lostandfound/admin.py | 1 - lostandfound/models.py | 8 ++-- 5 files changed, 34 insertions(+), 38 deletions(-) diff --git a/.flake8 b/.flake8 index be59c58b..55475c9a 100644 --- a/.flake8 +++ b/.flake8 @@ -1,5 +1,5 @@ [flake8] -exclude = .git,__pycache__,backend/settings*,*/migrations/*,venv,.venv +exclude = .git,__pycache__,backend/settings*,*/migrations/*,venv,.venv,adj_list.py ignore = E302,E731,W503 max-complexity = 15 max-line-length = 120 diff --git a/locations/management/commands/mapnav.py b/locations/management/commands/mapnav.py index 31628a01..64f4da6f 100644 --- a/locations/management/commands/mapnav.py +++ b/locations/management/commands/mapnav.py @@ -1,11 +1,12 @@ +import os +import sys +import math as m + from django.conf import settings from django.core.management.base import BaseCommand from django.db.models import Q -import sys from locations.serializers import LocationSerializerMin from locations.models import Location -import os -import math as m # class ProfileFetcher(): # """Helper to get dictionary of profiles efficiently.""" @@ -22,10 +23,9 @@ """ Returns adj_list with the distances and updates database for -Locations models to contain the node points(if they didn't). +Locations models to contain the node points (if they didn't). """ - class handle_entry: def __init__(self): self.coordinates = [ @@ -289,17 +289,18 @@ def __init__(self): self.adj_list = self.load_adj_list() - """Caution: Avoid executing the update function during active requests as it may cause significant delays (~20s). - If any modifications need to be made to the adj_list, it is essential to ensure that the - adj_list is updated accordingly, - including the distances between nodes. - """ - + # flake8: noqa: C901 def update(self): + """Caution: Avoid executing the update function during active requests as it may cause significant delays (~20s). + If any modifications need to be made to the adj_list, it is essential to ensure that the + adj_list is updated accordingly, + including the distances between nodes. + """ + for x in self.adj_list: - if type(x) != str: + if not isinstance(x, str): for y in self.adj_list[x]: - if type(y) != str: + if not isinstance(y, str): self.adj_list[x][y] = m.sqrt( abs( 0.001 @@ -346,7 +347,7 @@ def update(self): y_cor = 0 for y in self.adj_list[x]: - if type(y) != str: + if not isinstance(y, str): self.adj_list[x][y] = m.sqrt( abs( 0.001 @@ -386,11 +387,11 @@ def update(self): with open(adj_list_path, "w") as f: f.write(str(self.adj_list)) - """ - Updates the 'connected_locs' field of Location objects with conected locations - """ - def update_locations_with_connected_loc(self): + """ + Updates the 'connected_locs' field of Location objects with conected locations + """ + # Need to run this to ensure the location objects contain the adjacent locations that they are connected to. all_locations = Location.objects.all() for location in all_locations: @@ -408,8 +409,6 @@ def update_locations_with_connected_loc(self): except KeyError: pass - """Gets the nearest Node near a location on the map.""" - def load_adj_list(self): adj_list_path = f"{os.getcwd()}/locations/management/commands/adj_list.py" adj_list = {} @@ -419,9 +418,9 @@ def load_adj_list(self): return adj_list - import sys - def get_nearest(self, loc): + """Gets the nearest Node near a location on the map.""" + if "Node" in loc: k = int(loc.replace("Node", "")) return k @@ -441,9 +440,9 @@ def get_nearest(self, loc): return nearest_loc - """Returns the adj_list which contains only the node points containing the endpoint and the start point""" - def graph(self, end, start): + """Returns the adj_list which contains only the node points containing the endpoint and the start point""" + new_adjoint_list = {} for i in self.adj_list: if isinstance(i, int) or i == start or i == end: @@ -532,11 +531,9 @@ def handle(self, *args, **options): self.style.SUCCESS("External Blog Chore completed successfully") ) - -""" This command gets the nearest points for some x,y coordinates. Although a simliar function is defined in views.py""" - - def fn_nearest_points(request): + """ This command gets the nearest points for some x,y coordinates. Although a simliar function is defined in views.py""" + xcor = request.data2["xcor"] ycor = request.data2["ycor"] diff --git a/locations/views.py b/locations/views.py index 68648459..74d26354 100644 --- a/locations/views.py +++ b/locations/views.py @@ -135,7 +135,7 @@ def get_shortest_path(request): for a in range(len(path)): i = path[a] - if type(i) == str: + if isinstance(i, str): loc_i = Location.objects.get(name=i) else: name = "Node" + str(i) @@ -245,7 +245,7 @@ def nearest_points(request): @api_view(["GET"]) def checkerrors(request): adj_list = handle_entry().load_adj_list() # change this list accordingly - # adj_list ={} + items = {} items["Failed : Location Does Not Exist"] = [] items["Failed : MultipleObjectsReturned"] = [] @@ -254,7 +254,7 @@ def checkerrors(request): items["Passed : Coordinates are null"] = [] for x in adj_list: - if type(x) == str: + if isinstance(x, str): try: a = Location.objects.get(name=x) if a.pixel_x is None or a.pixel_y is None: @@ -266,7 +266,7 @@ def checkerrors(request): items["Failed : MultipleObjectsReturned"].append(x) for y in adj_list[x]: - if type(y) == str: + if isinstance(y, str): try: a = Location.objects.get(name=y) if a.pixel_x is None or a.pixel_y is None: diff --git a/lostandfound/admin.py b/lostandfound/admin.py index 5dea47b8..c4c7f2a5 100644 --- a/lostandfound/admin.py +++ b/lostandfound/admin.py @@ -67,7 +67,6 @@ class Meta: "product_image1", "product_image2", "product_image3", - ] self.form = CustomChangeForm diff --git a/lostandfound/models.py b/lostandfound/models.py index 0102aac8..4b0ef759 100644 --- a/lostandfound/models.py +++ b/lostandfound/models.py @@ -10,8 +10,9 @@ CONTACT_MAX_LENGTH = 300 def get_image_path(instance, filename): - random_str = "fd9a457a-a5b5-4560-b81e-6654129e5df8" # NOTE: Since we not using uploaded by - all the images are stored in the same folder. - return './' + random_str[0:4] + '/'+ random_str + '-' + filename + '.jpg' + # NOTE: Since we not using uploaded by - all the images are stored in the same folder. + random_str = "fd9a457a-a5b5-4560-b81e-6654129e5df8" + return './' + random_str[0:4] + '/' + random_str + '-' + filename + '.jpg' class ProductFound(models.Model): CATEGORY_CHOICES = ( @@ -63,7 +64,6 @@ def save(self, *args, **kwargs): self.str_id = get_url_friendly(self.name) + "-" + str(self.id)[:8] super().save(*args, **kwargs) - class Meta: verbose_name = "ProductFound" verbose_name_plural = "ProductsFound" @@ -83,7 +83,7 @@ def update_product_found(sender, instance, **kwargs): This is done to avoid the problem of the correct image url not being available.""" image_urls = "" image_urls += instance.product_image1.url + "," - if instance.product_image2: + if instance.product_image2: image_urls += instance.product_image2.url + "," if instance.product_image3: image_urls += instance.product_image3.url From b8b1f7d20b215c12fa2f4bef6e1244daf20266ea Mon Sep 17 00:00:00 2001 From: Varun Patil Date: Sun, 17 Mar 2024 16:04:01 -0700 Subject: [PATCH 2/2] chore: fix pylint --- .pylintrc | 2 +- bans/models.py | 5 +- bans/views.py | 28 ++++---- buyandsell/models.py | 6 +- buyandsell/views.py | 45 ++++++------ community/serializers.py | 2 +- community/views.py | 4 +- locations/management/commands/adj_updater.py | 12 ++-- locations/management/commands/mapnav.py | 75 +++++++------------- locations/views.py | 58 +++++++-------- lostandfound/admin.py | 3 - lostandfound/views.py | 13 ++-- roles/helpers.py | 35 +++++---- roles/models.py | 46 +++--------- 14 files changed, 136 insertions(+), 198 deletions(-) diff --git a/.pylintrc b/.pylintrc index 9faeba91..cff7d9d9 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,6 +1,6 @@ [MASTER] load-plugins=pylint_django -ignore=.git,__pycache__,backend,migrations,venv,.venv +ignore=.git,__pycache__,backend,migrations,venv,.venv,adj_list.py [MESSAGES CONTROL] max-line-length=120 diff --git a/bans/models.py b/bans/models.py index 047d2cb8..1859b310 100644 --- a/bans/models.py +++ b/bans/models.py @@ -1,10 +1,7 @@ -from django.db import models from uuid import uuid4 +from django.db import models from users.models import UserProfile -# Create your models here. - - BAN_REASON_CHOICHES = [ ("IDF", "Unappropriate Comment"), ("Buy&Sell", "Unappropriate Activity in Buy and Sell"), diff --git a/bans/views.py b/bans/views.py index fea4212d..2c07e340 100644 --- a/bans/views.py +++ b/bans/views.py @@ -9,15 +9,11 @@ forbidden_no_privileges, ) - from users.models import UserProfile from .models import SSOBan from .serializers import SSOBansSerializer -# Create your views here. - - class SSOBanViewSet(viewsets.ModelViewSet): queryset = SSOBan.objects.all() serializer_class = SSOBansSerializer @@ -29,8 +25,8 @@ def list(self, request): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) - else: - return forbidden_no_privileges() + + return forbidden_no_privileges() @login_required_ajax def retrieve(self, request, pk): @@ -38,8 +34,8 @@ def retrieve(self, request, pk): instance = get_object_or_404(self.queryset, pk=pk) serializer = self.get_serializer(instance) return Response(serializer.data) - else: - return forbidden_no_privileges() + + return forbidden_no_privileges() @login_required_ajax def create(self, request): @@ -69,11 +65,11 @@ def create(self, request): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - else: - return forbidden_no_privileges() + + return forbidden_no_privileges() @login_required_ajax - def update(self, request, pk=None, *args, **kwargs): + def update(self, request, *args, pk=None, **kwargs): if user_has_insti_privilege(request.user.profile, "RoleB"): instance = get_object_or_404(self.queryset, pk=pk) serializer = self.get_serializer(instance, data=request.data, partial=True) @@ -84,14 +80,14 @@ def update(self, request, pk=None, *args, **kwargs): return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - else: - return forbidden_no_privileges() + + return forbidden_no_privileges() @login_required_ajax - def destroy(self, request, pk=None, *args, **kwargs): + def destroy(self, request, *args, pk=None, **kwargs): if user_has_insti_privilege(request.user.profile, "RoleB"): instance = get_object_or_404(self.queryset, pk=pk) instance.delete() return Response(status=status.HTTP_204_NO_CONTENT) - else: - return forbidden_no_privileges() + + return forbidden_no_privileges() diff --git a/buyandsell/models.py b/buyandsell/models.py index bf14d4ce..295291fe 100644 --- a/buyandsell/models.py +++ b/buyandsell/models.py @@ -1,7 +1,9 @@ +from uuid import uuid4 + from django.db.models.deletion import SET from django.db.models.fields.related import ForeignKey from django.db import models -from uuid import uuid4 + from helpers.misc import get_url_friendly PDT_NAME_MAX_LENGTH = 60 @@ -49,7 +51,7 @@ class Product(models.Model): name = models.CharField(max_length=PDT_NAME_MAX_LENGTH, blank=False, null=False) description = models.TextField(blank=True, default="", null=False) product_image = models.TextField(blank=True, null=True) - # TODO: Change the on_delete function to . + # _TODO: Change the on_delete function to . category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True ) diff --git a/buyandsell/views.py b/buyandsell/views.py index 4d886a30..353883aa 100644 --- a/buyandsell/views.py +++ b/buyandsell/views.py @@ -1,17 +1,20 @@ """Views for BuyAndSell.""" +import json + from django.conf import settings from django.core.mail import send_mail +from django.shortcuts import get_object_or_404 +from django.db.models import Q +from django.utils import timezone + from rest_framework.response import Response from rest_framework import viewsets -from django.shortcuts import get_object_or_404 + from roles.helpers import login_required_ajax from buyandsell.models import Ban, Category, ImageURL, Limit, Product, Report from buyandsell.serializers import ProductSerializer from helpers.misc import query_search from users.models import UserProfile -from django.db.models import Q -import json -from django.utils import timezone REPORTS_THRES = 3 @@ -37,26 +40,26 @@ def update_limits(self): def update_bans(self, product: Product = None): if product is not None: - """Get the existing reports on this product that have been accepted by the moderator - but have not been addressed (by initiating a ban).""" + # Get the existing reports on this product that have been accepted by the moderator + # but have not been addressed (by initiating a ban). reports = Report.objects.filter( product=product, addressed=False, accepted=True ) if len(reports) >= REPORTS_THRES: - """Create a ban for the user lasting three days.""" + # Create a ban for the user lasting three days. endtime = timezone.localtime() + timezone.timedelta(days=3) Ban.objects.create(user=product.user, endtime=endtime) product.deleted = True reports.update(addressed=True) else: - """Calls the above if-block on products that have accepted but unaddressed reports.""" + # Calls the above if-block on products that have accepted but unaddressed reports. reports = Report.objects.filter(accepted=True, addressed=False) products = [] for report in reports: products.append(report.product) for prod in set(products): if products.count(prod) >= REPORTS_THRES: - """Products from a banned user cannot be reported. (acc. to report function.)""" + # Products from a banned user cannot be reported. (acc. to report function.) endtime = timezone.localtime() + timezone.timedelta(days=3) Ban.objects.create(user=product.user, endtime=endtime) reports.update(addressed=True) @@ -77,13 +80,13 @@ def list(self, request): # introduce tags? self.update_bans() queryset = self.queryset.filter(status=True) - """remove products from banned users""" + # remove products from banned users bans = Ban.objects.all() for ban in bans: if ban.endtime > timezone.localtime(): - """Remove products from users whose bans are still running.""" + # Remove products from users whose bans are still running. queryset = queryset.filter(~Q(user=ban.user)) - # TODO: allow category to be passed here too. + # _TODO: allow category to be passed here too. queryset = query_search( request, 3, queryset, ["name", "description"], "buyandsell" ) @@ -93,12 +96,15 @@ def list(self, request): data = ProductSerializer(queryset, many=True).data return Response(data) + @staticmethod def get_contact_details(userpro: UserProfile): return f""" Phone: {userpro.contact_no} Email: {userpro.email}""" - def update_image_urls(self, request, instance, image_urls=[]): + def update_image_urls(self, request, instance, image_urls=None): + if image_urls is None: + image_urls = [] if len(image_urls) == 0: image_urls = json.loads(request.data["image_urls"]) ImageURL.objects.filter(product=instance).delete() @@ -119,19 +125,18 @@ def create(self, request): """ self.update_limits() - from users.models import UserProfile userpro = UserProfile.objects.get(user=request.user) - """Limit checking:""" - limit, created = Limit.objects.get_or_create(user=userpro) + # Limit checking + limit, _ = Limit.objects.get_or_create(user=userpro) if limit.strikes >= 1000: return Response("Limit of Three Products per Day Reached.", status=403) limit.strikes += 1 if limit.strikes == 3: limit.endtime = timezone.localtime() + timezone.timedelta(days=1) limit.save() - """Create the product, modifying some fields.""" + # Create the product, modifying some fields # request.data._mutable = True # request.data['status'] = True # image_urls = json.loads(request.data['image_urls']) @@ -177,12 +182,12 @@ def report(self, request, pk): product = self.get_product(pk) self.update_bans(product) if len(Ban.objects.filter(user=product.user)) > 0: - """If user is banned, their products don't show up in the list. - This if-block is for calls made to the api manually.""" + # If user is banned, their products don't show up in the list. + # This if-block is for calls made to the api manually return Response("User is Banned atm.") reporter = UserProfile.objects.get(user=request.user) # reporter = product.user - report_by_user, created = Report.objects.get_or_create( + report_by_user, _ = Report.objects.get_or_create( product=product, reporter=reporter ) report_by_user: Report diff --git a/community/serializers.py b/community/serializers.py index 91a22b96..818354d1 100644 --- a/community/serializers.py +++ b/community/serializers.py @@ -3,8 +3,8 @@ from community.models import Community, CommunityPost from community.serializer_min import CommunityPostSerializerMin from roles.serializers import RoleSerializerMin -from users.models import UserProfile from bodies.models import Body +from users.models import UserProfile from users.serializers import UserProfileSerializer diff --git a/community/views.py b/community/views.py index df942298..1bafbad4 100644 --- a/community/views.py +++ b/community/views.py @@ -130,7 +130,7 @@ def create(self, request): if "community" not in request.data or not request.data["community"]: return forbidden_no_privileges() - user, created = UserProfile.objects.get_or_create(user=request.user) + UserProfile.objects.get_or_create(user=request.user) return super().create(request) @login_required_ajax @@ -253,7 +253,7 @@ def get_community(self, pk): @login_required_ajax def create(self, request): name = request.data["name"] - user, created = UserProfile.objects.get_or_create(user=request.user) + UserProfile.objects.get_or_create(user=request.user) if not Community.objects.all().filter(name=name).exists(): super().create(request) return Response({"message": "Community created"}) diff --git a/locations/management/commands/adj_updater.py b/locations/management/commands/adj_updater.py index 37407500..74a113f0 100644 --- a/locations/management/commands/adj_updater.py +++ b/locations/management/commands/adj_updater.py @@ -12,6 +12,7 @@ def load_adj_list(self): adj_list = {} with open(adj_list_path, "r") as f: + # pylint: disable=eval-used adj_list = dict(eval(f.read())) return adj_list @@ -33,11 +34,14 @@ def calculate_distance(loc1, loc2): return m.sqrt(0.001 * ((x_loc1 - x_loc2) ** 2 + (y_loc1 - y_loc2) ** 2)) - """ - This function updates the adj_list with the new connections and distances betweem them. - """ + def add_conns(self, loc1, connections=None): + """ + This function updates the adj_list with the new connections and distances betweem them. + """ + + if not connections: + connections = [] - def add_conns(self, loc1, connections=[]): new_data = self.adj_list.copy() for loc2 in connections: if loc2: diff --git a/locations/management/commands/mapnav.py b/locations/management/commands/mapnav.py index 64f4da6f..91374a79 100644 --- a/locations/management/commands/mapnav.py +++ b/locations/management/commands/mapnav.py @@ -2,30 +2,11 @@ import sys import math as m -from django.conf import settings from django.core.management.base import BaseCommand from django.db.models import Q from locations.serializers import LocationSerializerMin from locations.models import Location -# class ProfileFetcher(): -# """Helper to get dictionary of profiles efficiently.""" -# def __init__(self): -# self.roll_nos = None - -# def get_roll(self): -# if not self.roll_nos: -# self.roll_nos = UserProfile.objects.filter(active=True).values_list('roll_no', flat=True) -# return self.roll_nos - - -# profile_fetcher = ProfileFetcher() - -""" -Returns adj_list with the distances and updates database for -Locations models to contain the node points (if they didn't). -""" - class handle_entry: def __init__(self): self.coordinates = [ @@ -291,27 +272,21 @@ def __init__(self): # flake8: noqa: C901 def update(self): - """Caution: Avoid executing the update function during active requests as it may cause significant delays (~20s). - If any modifications need to be made to the adj_list, it is essential to ensure that the - adj_list is updated accordingly, - including the distances between nodes. + """Caution: Avoid executing the update function during active requests as + it may cause significant delays (~20s). If any modifications need to be + made to the adj_list, it is essential to ensure that the adj_list is + updated accordingly, including the distances between nodes. """ + # pylint: disable=consider-using-dict-items, too-many-branches, too-many-nested-blocks for x in self.adj_list: if not isinstance(x, str): for y in self.adj_list[x]: if not isinstance(y, str): self.adj_list[x][y] = m.sqrt( - abs( - 0.001 - * ( - (self.coordinates[x][0] - self.coordinates[y][0]) - ** 2 - + (self.coordinates[x][1] - self.coordinates[y][1]) - ** 2 - ) - ) - ) + abs(0.001 * ( + (self.coordinates[x][0] - self.coordinates[y][0]) ** 2 + + (self.coordinates[x][1] - self.coordinates[y][1]) ** 2))) else: try: x_cor = Location.objects.filter(name=y)[0].pixel_x @@ -376,9 +351,7 @@ def update(self): i = 0 loc_list = [] for p in self.coordinates: - loc, c = Location.objects.get_or_create( - pixel_x=p[0], pixel_y=p[1], name="Node" + str(i) - ) + loc, _ = Location.objects.get_or_create(pixel_x=p[0], pixel_y=p[1], name="Node" + str(i)) loc_list.append(loc) i += 1 @@ -414,7 +387,7 @@ def load_adj_list(self): adj_list = {} with open(adj_list_path, "r") as f: - adj_list = dict(eval(f.read())) + adj_list = dict(eval(f.read())) # pylint: disable=eval-used return adj_list @@ -422,8 +395,7 @@ def get_nearest(self, loc): """Gets the nearest Node near a location on the map.""" if "Node" in loc: - k = int(loc.replace("Node", "")) - return k + return int(loc.replace("Node", "")) min_dist = sys.maxsize nearest_loc = None @@ -444,7 +416,7 @@ def graph(self, end, start): """Returns the adj_list which contains only the node points containing the endpoint and the start point""" new_adjoint_list = {} - for i in self.adj_list: + for i in self.adj_list: # pylint: disable=consider-using-dict-items if isinstance(i, int) or i == start or i == end: new_adjoint_list[i] = {} for j in self.adj_list[i]: @@ -526,13 +498,16 @@ class Command(BaseCommand): def handle(self, *args, **options): """Run the chore.""" - handle_entry(settings.EXTERNAL_BLOG_URL) - self.stdout.write( - self.style.SUCCESS("External Blog Chore completed successfully") - ) + # not sure wth is happening here + handle_entry() + self.stdout.write(self.style.SUCCESS("External Blog Chore completed successfully")) def fn_nearest_points(request): - """ This command gets the nearest points for some x,y coordinates. Although a simliar function is defined in views.py""" + """ + This command gets the nearest points for some x,y coordinates. + Although a simliar function is defined in views.py + """ + # pylint: disable=too-many-branches xcor = request.data2["xcor"] ycor = request.data2["ycor"] @@ -543,16 +518,14 @@ def fn_nearest_points(request): xcor = int(xcor) ycor = int(ycor) except TypeError: - data = {"detail": "Invalid Coordinates "} - return data + return {"detail": "Invalid Coordinates "} + if "only_nodes" in request.data2: filtered_locations = Location.objects.filter( Q(name__contains="Node"), pixel_x__range=[xcor - 1200, xcor + 1200], pixel_y__range=[ycor - 1200, ycor + 1200], ) - # filtered_locations = location.filter - # (pixel_x__range=[xcor - 400, xcor + # 400], pixel_y__range=[ycor - 400, ycor # + 400]) else: location = Location filtered_locations = location.objects.filter( @@ -601,5 +574,5 @@ def fn_nearest_points(request): locations[1] = LocationSerializerMin(filtered_locations[snpi]).data return locations - else: - return {"detail": "No Locations"} + + return {"detail": "No Locations"} diff --git a/locations/views.py b/locations/views.py index 74d26354..adca564f 100644 --- a/locations/views.py +++ b/locations/views.py @@ -1,21 +1,21 @@ """Views for locations app.""" +import sys + +from django.db.models import Q +from django.http import HttpRequest from rest_framework import viewsets from rest_framework.response import Response +from rest_framework.decorators import api_view + from locations.serializers import LocationSerializer from locations.models import Location +from locations.management.commands.mapnav import handle_entry, dijkstra + from roles.helpers import insti_permission_required from roles.helpers import login_required_ajax from roles.helpers import user_has_insti_privilege from roles.helpers import user_has_privilege from roles.helpers import forbidden_no_privileges -from django.db.models import Q -from django.http import HttpRequest -import sys -from rest_framework.decorators import api_view -from locations.management.commands.mapnav import ( - handle_entry, - dijkstra, -) class LocationViewSet(viewsets.ModelViewSet): @@ -79,14 +79,12 @@ def destroy(self, request, pk): return super().destroy(request, pk) - -""" -This endpoint gives the shortest path between two points on the map in a sequence of locations. -""" - - @api_view(("POST",)) def get_shortest_path(request): + """ + This endpoint gives the shortest path between two points on the map in a sequence of locations. + """ + try: start = request.data["origin"] formatted_origin = True @@ -133,8 +131,7 @@ def get_shortest_path(request): ] ) - for a in range(len(path)): - i = path[a] + for _, i in enumerate(path): if isinstance(i, str): loc_i = Location.objects.get(name=i) else: @@ -157,14 +154,14 @@ def get_shortest_path(request): return Response(data={"detail": "No path found"}) return Response() - -""" -Finding the nearest two points for a given set of coordinates. -""" - - @api_view(("POST",)) def nearest_points(request): + """ + Finding the nearest two points for a given set of coordinates. + """ + + # pylint: disable=too-many-branches + xcor = request.data["xcor"] ycor = request.data["ycor"] @@ -182,8 +179,6 @@ def nearest_points(request): pixel_x__range=[xcor - 1200, xcor + 1200], pixel_y__range=[ycor - 1200, ycor + 1200], ) - # filtered_locations = location.filter( - # pixel_x__range=[xcor - 400, xcor + 400], pixel_y__range=[ycor - 400, ycor + 400]) else: location = Location filtered_locations = location.objects.filter( @@ -232,18 +227,16 @@ def nearest_points(request): locations[1] = LocationSerializer(filtered_locations[snpi]).data return Response(data=locations) - else: - return Response(data={"detail": "No Locations"}) - - -""" -"Testing errors in the adjacency list: -These are the errors that may occur when running the Dijkstra code. It provides common error outputs." -""" + return Response(data={"detail": "No Locations"}) @api_view(["GET"]) def checkerrors(request): + """ + Testing errors in the adjacency list: + These are the errors that may occur when running the Dijkstra code. It provides common error outputs." + """ + adj_list = handle_entry().load_adj_list() # change this list accordingly items = {} @@ -253,6 +246,7 @@ def checkerrors(request): items["Passed : Coordinates null"] = [] items["Passed : Coordinates are null"] = [] + # pylint: disable=consider-using-dict-items for x in adj_list: if isinstance(x, str): try: diff --git a/lostandfound/admin.py b/lostandfound/admin.py index c4c7f2a5..df137bf5 100644 --- a/lostandfound/admin.py +++ b/lostandfound/admin.py @@ -72,9 +72,6 @@ class Meta: self.form = CustomChangeForm return super().change_view(request, object_id, form_url, extra_context) - def save_model(self, request, obj, form, change): - super().save_model(request, obj, form, change) - class CSOAdminSite(admin.AdminSite): site_header = "CSO Admin" site_title = "CSO Admin Portal" diff --git a/lostandfound/views.py b/lostandfound/views.py index f6e11a93..5e55e6c7 100644 --- a/lostandfound/views.py +++ b/lostandfound/views.py @@ -1,12 +1,15 @@ """Views for BuyAndSell.""" from uuid import UUID -from rest_framework.response import Response -from rest_framework import viewsets from django.shortcuts import get_object_or_404 -from roles.helpers import login_required_ajax from django.contrib.auth.decorators import login_required from django.shortcuts import redirect + +from rest_framework.response import Response +from rest_framework import viewsets + +from roles.helpers import login_required_ajax + from lostandfound.models import ProductFound from lostandfound.serializers import ProductFoundSerializer @@ -56,5 +59,5 @@ def claim(self, request, *args, **kwargs): def cso_admin_login(request): if request.user.is_staff: return redirect("CSOAdmin:index") - else: - return Response({"message": "Not a staff member"}, status=401) + + return Response({"message": "Not a staff member"}, status=401) diff --git a/roles/helpers.py b/roles/helpers.py index 37500e52..1557b02a 100644 --- a/roles/helpers.py +++ b/roles/helpers.py @@ -1,12 +1,13 @@ """Helper functions for implementing roles.""" +import datetime +from dateutil.relativedelta import relativedelta + from rest_framework.response import Response + from bodies.models import Body -from community.models import Community from bans.models import SSOBan +from community.models import Community from users.models import UserProfile -import datetime -from dateutil.relativedelta import relativedelta - def user_is_banned(profile): try: @@ -18,17 +19,16 @@ def user_is_banned(profile): if ban_duration == "Permanent": return True - else: - duration_month = int(ban_duration.split(" ")[0]) - banned_till = ban_created + relativedelta(months=duration_month) + duration_month = int(ban_duration.split(" ")[0]) + banned_till = ban_created + relativedelta(months=duration_month) + + if banned_till > current_time: + return True - if banned_till > current_time: - return True return False except SSOBan.DoesNotExist: return False - def forbidden_no_privileges(): """Forbidden due to insufficient privileges.""" return Response( @@ -107,15 +107,12 @@ def wrapper(*args, **kw): if args[1].user.is_authenticated: user = args[1].user profile = UserProfile.objects.get(user=user) - if not user_is_banned(profile): - return func(*args, **kw) - if user_is_banned: - return Response( - {"message": "banned", "detail": "your SSO has been banned/disabled"} - ) - return Response( - {"message": "unauthenticated", "detail": "Log in to continue!"}, status=401 - ) + if user_is_banned(profile): + return Response({"message": "banned", "detail": "your SSO has been banned/disabled"}) + + return func(*args, **kw) + + return Response({"message": "unauthenticated", "detail": "Log in to continue!"}, status=401) return wrapper diff --git a/roles/models.py b/roles/models.py index 9f87d400..b117119e 100644 --- a/roles/models.py +++ b/roles/models.py @@ -14,6 +14,14 @@ ("ModC", "Moderate Comment"), ) +INSTITUTE_PERMISSION_CHOICES = ( + ("AddB", "Add Body"), + ("DelB", "Delete Body"), + ("BodyChild", "Modify Body-Child Relations"), + ("Location", "Full control over locations"), + ("Role", "Modify Institute Roles"), + ("RoleB", "Modify roles for any body"), +) class BodyRole(models.Model): """A role for a bodywhich can be granted to multiple users.""" @@ -38,44 +46,6 @@ class Meta: def __str__(self): return self.body.name + " " + self.name - -""" -Added Community Role Model : To allow to have various communities in a single body and have different roles for each -community. -Ditched For Now -""" -# class CommunityRole(models.Model): -# """A role for a bodywhich can be granted to multiple users.""" - -# id = models.UUIDField(primary_key=True, default=uuid4, editable=False) -# time_of_creation = models.DateTimeField(auto_now_add=True) -# name = models.CharField(max_length=50) -# community = models.ForeignKey('community.Community', on_delete=models.CASCADE, related_name='roles') -# inheritable = models.BooleanField(default=False) -# permissions = MultiSelectField(choices=PERMISSION_CHOICES) -# priority = models.IntegerField(default=0) -# official_post = models.BooleanField(default=True) -# permanent = models.BooleanField(default=False) - -# class Meta: -# verbose_name = "Community Role" -# verbose_name_plural = "Community Roles" -# ordering = ("community__name", "priority") - -# def __str__(self): -# return self.community.name + " " + self.name - - -INSTITUTE_PERMISSION_CHOICES = ( - ("AddB", "Add Body"), - ("DelB", "Delete Body"), - ("BodyChild", "Modify Body-Child Relations"), - ("Location", "Full control over locations"), - ("Role", "Modify Institute Roles"), - ("RoleB", "Modify roles for any body"), -) - - class InstituteRole(models.Model): """An institute role which can be granted to multiple users."""