dev: code improvements and minor performance upgrades (#2201)

* dev: remove len for empty comparison

* dev: using in instead of multiple ors

* dev: assign expression to empty variables

* dev: use f-string

* dev: remove list comprehension and use generators

* dev: remove assert from paginator

* dev: use is for identity comparison with singleton

* dev: remove unnecessary else statements

* dev: fix does not exists error for both project and workspace

* dev: remove reimports

* dev: iterate a dictionary

* dev: remove unused commented code

* dev: remove redefinition

* dev: remove unused imports

* dev: remove unused imports

* dev: remove unnecessary f strings

* dev: remove unused variables

* dev: use literal structure to create the data structure

* dev: add empty lines at the end of the file

* dev: remove user middleware

* dev: remove unnecessary default None
This commit is contained in:
Nikhil 2023-11-01 20:35:06 +05:30 committed by GitHub
parent d63e7cf254
commit 7249f84e18
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 51 additions and 157 deletions

View File

@ -1,4 +1,4 @@
import os, sys, random, string import os, sys
import uuid import uuid
sys.path.append("/code") sys.path.append("/code")

View File

@ -17,7 +17,7 @@ class AnalyticViewSerializer(BaseSerializer):
if bool(query_params): if bool(query_params):
validated_data["query"] = issue_filters(query_params, "POST") validated_data["query"] = issue_filters(query_params, "POST")
else: else:
validated_data["query"] = dict() validated_data["query"] = {}
return AnalyticView.objects.create(**validated_data) return AnalyticView.objects.create(**validated_data)
def update(self, instance, validated_data): def update(self, instance, validated_data):
@ -25,6 +25,6 @@ class AnalyticViewSerializer(BaseSerializer):
if bool(query_params): if bool(query_params):
validated_data["query"] = issue_filters(query_params, "POST") validated_data["query"] = issue_filters(query_params, "POST")
else: else:
validated_data["query"] = dict() validated_data["query"] = {}
validated_data["query"] = issue_filters(query_params, "PATCH") validated_data["query"] = issue_filters(query_params, "PATCH")
return super().update(instance, validated_data) return super().update(instance, validated_data)

View File

@ -1,6 +1,3 @@
# Django imports
from django.db.models.functions import TruncDate
# Third party imports # Third party imports
from rest_framework import serializers from rest_framework import serializers

View File

@ -6,7 +6,6 @@ from .base import BaseSerializer
from .issue import IssueFlatSerializer, LabelLiteSerializer from .issue import IssueFlatSerializer, LabelLiteSerializer
from .project import ProjectLiteSerializer from .project import ProjectLiteSerializer
from .state import StateLiteSerializer from .state import StateLiteSerializer
from .project import ProjectLiteSerializer
from .user import UserLiteSerializer from .user import UserLiteSerializer
from plane.db.models import Inbox, InboxIssue, Issue from plane.db.models import Inbox, InboxIssue, Issue

View File

@ -8,8 +8,7 @@ from rest_framework import serializers
from .base import BaseSerializer from .base import BaseSerializer
from .user import UserLiteSerializer from .user import UserLiteSerializer
from .state import StateSerializer, StateLiteSerializer from .state import StateSerializer, StateLiteSerializer
from .user import UserLiteSerializer from .project import ProjectLiteSerializer
from .project import ProjectSerializer, ProjectLiteSerializer
from .workspace import WorkspaceLiteSerializer from .workspace import WorkspaceLiteSerializer
from plane.db.models import ( from plane.db.models import (
User, User,
@ -232,25 +231,6 @@ class IssueActivitySerializer(BaseSerializer):
fields = "__all__" fields = "__all__"
class IssueCommentSerializer(BaseSerializer):
actor_detail = UserLiteSerializer(read_only=True, source="actor")
issue_detail = IssueFlatSerializer(read_only=True, source="issue")
project_detail = ProjectLiteSerializer(read_only=True, source="project")
workspace_detail = WorkspaceLiteSerializer(read_only=True, source="workspace")
class Meta:
model = IssueComment
fields = "__all__"
read_only_fields = [
"workspace",
"project",
"issue",
"created_by",
"updated_by",
"created_at",
"updated_at",
]
class IssuePropertySerializer(BaseSerializer): class IssuePropertySerializer(BaseSerializer):
class Meta: class Meta:
@ -287,7 +267,6 @@ class LabelLiteSerializer(BaseSerializer):
class IssueLabelSerializer(BaseSerializer): class IssueLabelSerializer(BaseSerializer):
# label_details = LabelSerializer(read_only=True, source="label")
class Meta: class Meta:
model = IssueLabel model = IssueLabel

View File

@ -4,9 +4,8 @@ from rest_framework import serializers
# Module imports # Module imports
from .base import BaseSerializer from .base import BaseSerializer
from .user import UserLiteSerializer from .user import UserLiteSerializer
from .project import ProjectSerializer, ProjectLiteSerializer from .project import ProjectLiteSerializer
from .workspace import WorkspaceLiteSerializer from .workspace import WorkspaceLiteSerializer
from .issue import IssueStateSerializer
from plane.db.models import ( from plane.db.models import (
User, User,

View File

@ -57,7 +57,7 @@ class IssueViewSerializer(BaseSerializer):
if bool(query_params): if bool(query_params):
validated_data["query"] = issue_filters(query_params, "POST") validated_data["query"] = issue_filters(query_params, "POST")
else: else:
validated_data["query"] = dict() validated_data["query"] = {}
return IssueView.objects.create(**validated_data) return IssueView.objects.create(**validated_data)
def update(self, instance, validated_data): def update(self, instance, validated_data):
@ -65,7 +65,7 @@ class IssueViewSerializer(BaseSerializer):
if bool(query_params): if bool(query_params):
validated_data["query"] = issue_filters(query_params, "POST") validated_data["query"] = issue_filters(query_params, "POST")
else: else:
validated_data["query"] = dict() validated_data["query"] = {}
validated_data["query"] = issue_filters(query_params, "PATCH") validated_data["query"] = issue_filters(query_params, "PATCH")
return super().update(instance, validated_data) return super().update(instance, validated_data)

View File

@ -110,7 +110,6 @@ class TeamSerializer(BaseSerializer):
] ]
TeamMember.objects.bulk_create(team_members, batch_size=10) TeamMember.objects.bulk_create(team_members, batch_size=10)
return team return team
else:
team = Team.objects.create(**validated_data) team = Team.objects.create(**validated_data)
return team return team
@ -124,7 +123,6 @@ class TeamSerializer(BaseSerializer):
] ]
TeamMember.objects.bulk_create(team_members, batch_size=10) TeamMember.objects.bulk_create(team_members, batch_size=10)
return super().update(instance, validated_data) return super().update(instance, validated_data)
else:
return super().update(instance, validated_data) return super().update(instance, validated_data)

View File

@ -28,7 +28,6 @@ from plane.api.views import (
## End User ## End User
# Workspaces # Workspaces
WorkSpaceViewSet, WorkSpaceViewSet,
UserWorkspaceInvitationsEndpoint,
UserWorkSpacesEndpoint, UserWorkSpacesEndpoint,
InviteWorkspaceEndpoint, InviteWorkspaceEndpoint,
JoinWorkspaceEndpoint, JoinWorkspaceEndpoint,

View File

@ -55,11 +55,11 @@ class VerifyEmailEndpoint(BaseAPIView):
return Response( return Response(
{"email": "Successfully activated"}, status=status.HTTP_200_OK {"email": "Successfully activated"}, status=status.HTTP_200_OK
) )
except jwt.ExpiredSignatureError as indentifier: except jwt.ExpiredSignatureError as _indentifier:
return Response( return Response(
{"email": "Activation expired"}, status=status.HTTP_400_BAD_REQUEST {"email": "Activation expired"}, status=status.HTTP_400_BAD_REQUEST
) )
except jwt.exceptions.DecodeError as indentifier: except jwt.exceptions.DecodeError as _indentifier:
return Response( return Response(
{"email": "Invalid token"}, status=status.HTTP_400_BAD_REQUEST {"email": "Invalid token"}, status=status.HTTP_400_BAD_REQUEST
) )

View File

@ -3,7 +3,6 @@ import json
# Django imports # Django imports
from django.db.models import ( from django.db.models import (
OuterRef,
Func, Func,
F, F,
Q, Q,

View File

@ -360,7 +360,6 @@ class InboxIssuePublicViewSet(BaseViewSet):
) )
.select_related("issue", "workspace", "project") .select_related("issue", "workspace", "project")
) )
else:
return InboxIssue.objects.none() return InboxIssue.objects.none()
def list(self, request, slug, project_id, inbox_id): def list(self, request, slug, project_id, inbox_id):

View File

@ -39,7 +39,6 @@ from plane.api.serializers import (
IssueActivitySerializer, IssueActivitySerializer,
IssueCommentSerializer, IssueCommentSerializer,
IssuePropertySerializer, IssuePropertySerializer,
LabelSerializer,
IssueSerializer, IssueSerializer,
LabelSerializer, LabelSerializer,
IssueFlatSerializer, IssueFlatSerializer,
@ -1392,7 +1391,6 @@ class IssueCommentPublicViewSet(BaseViewSet):
) )
.distinct() .distinct()
).order_by("created_at") ).order_by("created_at")
else:
return IssueComment.objects.none() return IssueComment.objects.none()
except ProjectDeployBoard.DoesNotExist: except ProjectDeployBoard.DoesNotExist:
return IssueComment.objects.none() return IssueComment.objects.none()
@ -1518,7 +1516,6 @@ class IssueReactionPublicViewSet(BaseViewSet):
.order_by("-created_at") .order_by("-created_at")
.distinct() .distinct()
) )
else:
return IssueReaction.objects.none() return IssueReaction.objects.none()
except ProjectDeployBoard.DoesNotExist: except ProjectDeployBoard.DoesNotExist:
return IssueReaction.objects.none() return IssueReaction.objects.none()
@ -1614,7 +1611,6 @@ class CommentReactionPublicViewSet(BaseViewSet):
.order_by("-created_at") .order_by("-created_at")
.distinct() .distinct()
) )
else:
return CommentReaction.objects.none() return CommentReaction.objects.none()
except ProjectDeployBoard.DoesNotExist: except ProjectDeployBoard.DoesNotExist:
return CommentReaction.objects.none() return CommentReaction.objects.none()
@ -1709,7 +1705,6 @@ class IssueVotePublicViewSet(BaseViewSet):
.filter(workspace__slug=self.kwargs.get("slug")) .filter(workspace__slug=self.kwargs.get("slug"))
.filter(project_id=self.kwargs.get("project_id")) .filter(project_id=self.kwargs.get("project_id"))
) )
else:
return IssueVote.objects.none() return IssueVote.objects.none()
except ProjectDeployBoard.DoesNotExist: except ProjectDeployBoard.DoesNotExist:
return IssueVote.objects.none() return IssueVote.objects.none()

View File

@ -11,7 +11,6 @@ from django.conf import settings
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework import exceptions from rest_framework import exceptions
from rest_framework.permissions import AllowAny from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework import status from rest_framework import status
from sentry_sdk import capture_exception from sentry_sdk import capture_exception
@ -113,7 +112,7 @@ def get_user_data(access_token: str) -> dict:
url="https://api.github.com/user/emails", headers=headers url="https://api.github.com/user/emails", headers=headers
).json() ).json()
[ _ = [
user_data.update({"email": item.get("email")}) user_data.update({"email": item.get("email")})
for item in response for item in response
if item.get("primary") is True if item.get("primary") is True
@ -147,7 +146,7 @@ class OauthEndpoint(BaseAPIView):
data = get_user_data(access_token) data = get_user_data(access_token)
email = data.get("email", None) email = data.get("email", None)
if email == None: if email is None:
return Response( return Response(
{ {
"error": "Something went wrong. Please try again later or contact the support team." "error": "Something went wrong. Please try again later or contact the support team."
@ -158,7 +157,6 @@ class OauthEndpoint(BaseAPIView):
if "@" in email: if "@" in email:
user = User.objects.get(email=email) user = User.objects.get(email=email)
email = data["email"] email = data["email"]
channel = "email"
mobile_number = uuid.uuid4().hex mobile_number = uuid.uuid4().hex
email_verified = True email_verified = True
else: else:
@ -182,7 +180,7 @@ class OauthEndpoint(BaseAPIView):
user.last_active = timezone.now() user.last_active = timezone.now()
user.last_login_time = timezone.now() user.last_login_time = timezone.now()
user.last_login_ip = request.META.get("REMOTE_ADDR") user.last_login_ip = request.META.get("REMOTE_ADDR")
user.last_login_medium = f"oauth" user.last_login_medium = "oauth"
user.last_login_uagent = request.META.get("HTTP_USER_AGENT") user.last_login_uagent = request.META.get("HTTP_USER_AGENT")
user.is_email_verified = email_verified user.is_email_verified = email_verified
user.save() user.save()
@ -233,7 +231,6 @@ class OauthEndpoint(BaseAPIView):
if "@" in email: if "@" in email:
email = data["email"] email = data["email"]
mobile_number = uuid.uuid4().hex mobile_number = uuid.uuid4().hex
channel = "email"
email_verified = True email_verified = True
else: else:
return Response( return Response(

View File

@ -1,5 +1,5 @@
# Python imports # Python imports
from datetime import timedelta, datetime, date from datetime import timedelta, date
# Django imports # Django imports
from django.db.models import Exists, OuterRef, Q, Prefetch from django.db.models import Exists, OuterRef, Q, Prefetch

View File

@ -11,7 +11,6 @@ from django.db.models import (
Q, Q,
Exists, Exists,
OuterRef, OuterRef,
Func,
F, F,
Func, Func,
Subquery, Subquery,
@ -35,7 +34,6 @@ from plane.api.serializers import (
ProjectDetailSerializer, ProjectDetailSerializer,
ProjectMemberInviteSerializer, ProjectMemberInviteSerializer,
ProjectFavoriteSerializer, ProjectFavoriteSerializer,
IssueLiteSerializer,
ProjectDeployBoardSerializer, ProjectDeployBoardSerializer,
ProjectMemberAdminSerializer, ProjectMemberAdminSerializer,
) )
@ -84,7 +82,7 @@ class ProjectViewSet(BaseViewSet):
] ]
def get_serializer_class(self, *args, **kwargs): def get_serializer_class(self, *args, **kwargs):
if self.action == "update" or self.action == "partial_update": if self.action in ["update", "partial_update"]:
return ProjectSerializer return ProjectSerializer
return ProjectDetailSerializer return ProjectDetailSerializer
@ -336,7 +334,7 @@ class ProjectViewSet(BaseViewSet):
{"name": "The project name is already taken"}, {"name": "The project name is already taken"},
status=status.HTTP_410_GONE, status=status.HTTP_410_GONE,
) )
except Project.DoesNotExist or Workspace.DoesNotExist as e: except (Project.DoesNotExist, Workspace.DoesNotExist):
return Response( return Response(
{"error": "Project does not exist"}, status=status.HTTP_404_NOT_FOUND {"error": "Project does not exist"}, status=status.HTTP_404_NOT_FOUND
) )

View File

@ -19,7 +19,6 @@ from plane.db.models import (
WorkspaceMemberInvite, WorkspaceMemberInvite,
Issue, Issue,
IssueActivity, IssueActivity,
WorkspaceMember,
) )
from plane.utils.paginator import BasePaginator from plane.utils.paginator import BasePaginator

View File

@ -6,12 +6,10 @@ from uuid import uuid4
# Django imports # Django imports
from django.db import IntegrityError from django.db import IntegrityError
from django.db.models import Prefetch
from django.conf import settings from django.conf import settings
from django.utils import timezone from django.utils import timezone
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.validators import validate_email from django.core.validators import validate_email
from django.contrib.sites.shortcuts import get_current_site
from django.db.models import ( from django.db.models import (
Prefetch, Prefetch,
OuterRef, OuterRef,
@ -55,7 +53,6 @@ from . import BaseViewSet
from plane.db.models import ( from plane.db.models import (
User, User,
Workspace, Workspace,
WorkspaceMember,
WorkspaceMemberInvite, WorkspaceMemberInvite,
Team, Team,
ProjectMember, ProjectMember,

View File

@ -23,7 +23,7 @@ def email_verification(first_name, email, token, current_site):
from_email_string = settings.EMAIL_FROM from_email_string = settings.EMAIL_FROM
subject = f"Verify your Email!" subject = "Verify your Email!"
context = { context = {
"first_name": first_name, "first_name": first_name,

View File

@ -4,7 +4,6 @@ import io
import json import json
import boto3 import boto3
import zipfile import zipfile
from urllib.parse import urlparse, urlunparse
# Django imports # Django imports
from django.conf import settings from django.conf import settings

View File

@ -8,8 +8,6 @@ from django.conf import settings
from celery import shared_task from celery import shared_task
from sentry_sdk import capture_exception from sentry_sdk import capture_exception
# Module imports
from plane.db.models import User
@shared_task @shared_task
@ -21,7 +19,7 @@ def forgot_password(first_name, email, uidb64, token, current_site):
from_email_string = settings.EMAIL_FROM from_email_string = settings.EMAIL_FROM
subject = f"Reset Your Password - Plane" subject = "Reset Your Password - Plane"
context = { context = {
"first_name": first_name, "first_name": first_name,

View File

@ -2,8 +2,6 @@
import json import json
import requests import requests
import uuid import uuid
import jwt
from datetime import datetime
# Django imports # Django imports
from django.conf import settings from django.conf import settings
@ -27,7 +25,6 @@ from plane.db.models import (
User, User,
IssueProperty, IssueProperty,
) )
from .workspace_invitation_task import workspace_invitation
from plane.bgtasks.user_welcome_task import send_welcome_slack from plane.bgtasks.user_welcome_task import send_welcome_slack
@ -58,7 +55,7 @@ def service_importer(service, importer_id):
ignore_conflicts=True, ignore_conflicts=True,
) )
[ _ = [
send_welcome_slack.delay( send_welcome_slack.delay(
str(user.id), str(user.id),
True, True,
@ -157,7 +154,7 @@ def service_importer(service, importer_id):
) )
# Create repo sync # Create repo sync
repo_sync = GithubRepositorySync.objects.create( _ = GithubRepositorySync.objects.create(
repository=repo, repository=repo,
workspace_integration=workspace_integration, workspace_integration=workspace_integration,
actor=workspace_integration.actor, actor=workspace_integration.actor,
@ -179,7 +176,7 @@ def service_importer(service, importer_id):
ImporterSerializer(importer).data, ImporterSerializer(importer).data,
cls=DjangoJSONEncoder, cls=DjangoJSONEncoder,
) )
res = requests.post( _ = requests.post(
f"{settings.PROXY_BASE_URL}/hooks/workspaces/{str(importer.workspace_id)}/projects/{str(importer.project_id)}/importers/{str(service)}/", f"{settings.PROXY_BASE_URL}/hooks/workspaces/{str(importer.workspace_id)}/projects/{str(importer.project_id)}/importers/{str(service)}/",
json=import_data_json, json=import_data_json,
headers=headers, headers=headers,

View File

@ -537,7 +537,7 @@ def update_issue_activity(
) )
for key in requested_data: for key in requested_data:
func = ISSUE_ACTIVITY_MAPPER.get(key, None) func = ISSUE_ACTIVITY_MAPPER.get(key)
if func is not None: if func is not None:
func( func(
requested_data=requested_data, requested_data=requested_data,

View File

@ -17,7 +17,7 @@ def magic_link(email, key, token, current_site):
from_email_string = settings.EMAIL_FROM from_email_string = settings.EMAIL_FROM
subject = f"Login for Plane" subject = "Login for Plane"
context = {"magic_url": abs_url, "code": token} context = {"magic_url": abs_url, "code": token}

View File

@ -11,7 +11,7 @@ from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError from slack_sdk.errors import SlackApiError
# Module imports # Module imports
from plane.db.models import Workspace, User, WorkspaceMemberInvite from plane.db.models import Workspace, WorkspaceMemberInvite
@shared_task @shared_task

View File

@ -27,7 +27,6 @@ from .issue import (
IssueActivity, IssueActivity,
IssueProperty, IssueProperty,
IssueComment, IssueComment,
IssueBlocker,
IssueLabel, IssueLabel,
IssueAssignee, IssueAssignee,
Label, Label,

View File

@ -6,7 +6,6 @@ from django.db import models
# Module imports # Module imports
from plane.db.models import ProjectBaseModel from plane.db.models import ProjectBaseModel
from plane.db.mixins import AuditModel
class GithubRepository(ProjectBaseModel): class GithubRepository(ProjectBaseModel):

View File

@ -4,9 +4,6 @@ from uuid import uuid4
# Django imports # Django imports
from django.db import models from django.db import models
from django.conf import settings from django.conf import settings
from django.template.defaultfilters import slugify
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator, MaxValueValidator from django.core.validators import MinValueValidator, MaxValueValidator
# Modeule imports # Modeule imports

View File

@ -1,33 +0,0 @@
import jwt
import pytz
from django.conf import settings
from django.utils import timezone
from plane.db.models import User
class UserMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
if request.headers.get("Authorization"):
authorization_header = request.headers.get("Authorization")
access_token = authorization_header.split(" ")[1]
decoded = jwt.decode(
access_token, settings.SECRET_KEY, algorithms=["HS256"]
)
id = decoded['user_id']
user = User.objects.get(id=id)
user.last_active = timezone.now()
user.token_updated_at = None
user.save()
timezone.activate(pytz.timezone(user.user_timezone))
except Exception as e:
print(e)
response = self.get_response(request)
return response

View File

@ -4,7 +4,6 @@ import ssl
import certifi import certifi
import dj_database_url import dj_database_url
from urllib.parse import urlparse
import sentry_sdk import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.django import DjangoIntegration

View File

@ -2,16 +2,13 @@
""" """
# from django.contrib import admin
from django.urls import path, include, re_path from django.urls import path, include, re_path
from django.views.generic import TemplateView from django.views.generic import TemplateView
from django.conf import settings from django.conf import settings
# from django.conf.urls.static import static
urlpatterns = [ urlpatterns = [
# path("admin/", admin.site.urls),
path("", TemplateView.as_view(template_name="index.html")), path("", TemplateView.as_view(template_name="index.html")),
path("api/", include("plane.api.urls")), path("api/", include("plane.api.urls")),
path("", include("plane.web.urls")), path("", include("plane.web.urls")),

View File

@ -81,7 +81,6 @@ def burndown_plot(queryset, slug, project_id, cycle_id=None, module_id=None):
# Total Issues in Cycle or Module # Total Issues in Cycle or Module
total_issues = queryset.total_issues total_issues = queryset.total_issues
if cycle_id: if cycle_id:
# Get all dates between the two dates # Get all dates between the two dates
date_range = [ date_range = [
@ -126,16 +125,13 @@ def burndown_plot(queryset, slug, project_id, cycle_id=None, module_id=None):
.order_by("date") .order_by("date")
) )
for date in date_range: for date in date_range:
cumulative_pending_issues = total_issues cumulative_pending_issues = total_issues
total_completed = 0 total_completed = 0
total_completed = sum( total_completed = sum(
[
item["total_completed"] item["total_completed"]
for item in completed_issues_distribution for item in completed_issues_distribution
if item["date"] is not None and item["date"] <= date if item["date"] is not None and item["date"] <= date
]
) )
cumulative_pending_issues -= total_completed cumulative_pending_issues -= total_completed
chart_data[str(date)] = cumulative_pending_issues chart_data[str(date)] = cumulative_pending_issues

View File

@ -127,7 +127,7 @@ def group_results(results_data, group_by, sub_group_by=False):
return main_responsive_dict return main_responsive_dict
else: else:
response_dict = dict() response_dict = {}
if group_by == "priority": if group_by == "priority":
response_dict = { response_dict = {

View File

@ -327,7 +327,7 @@ def filter_start_target_date_issues(params, filter, method):
def issue_filters(query_params, method): def issue_filters(query_params, method):
filter = dict() filter = {}
ISSUE_FILTER = { ISSUE_FILTER = {
"state": filter_state, "state": filter_state,

View File

@ -21,12 +21,7 @@ class Cursor:
) )
def __repr__(self): def __repr__(self):
return "<{}: value={} offset={} is_prev={}>".format( return f"{type(self).__name__,}: value={self.value} offset={self.offset}, is_prev={int(self.is_prev)}"
type(self).__name__,
self.value,
self.offset,
int(self.is_prev),
)
def __bool__(self): def __bool__(self):
return bool(self.has_results) return bool(self.has_results)
@ -176,10 +171,6 @@ class BasePaginator:
**paginator_kwargs, **paginator_kwargs,
): ):
"""Paginate the request""" """Paginate the request"""
assert (paginator and not paginator_kwargs) or (
paginator_cls and paginator_kwargs
)
per_page = self.get_per_page(request, default_per_page, max_per_page) per_page = self.get_per_page(request, default_per_page, max_per_page)
# Convert the cursor value to integer and float from string # Convert the cursor value to integer and float from string