lib.itmens/common/utils.py

75 lines
2.5 KiB
Python
Raw Normal View History

2021-08-01 12:36:03 +02:00
import uuid
from django.utils import timezone
2023-01-11 19:11:31 -05:00
2020-07-03 15:36:23 +08:00
class PageLinksGenerator:
# TODO inherit django paginator
"""
Calculate the pages for multiple links pagination.
length -- the number of page links in pagination
"""
2023-01-11 19:11:31 -05:00
2020-07-03 15:36:23 +08:00
def __init__(self, length, current_page, total_pages):
current_page = int(current_page)
self.current_page = current_page
2022-01-22 14:04:21 -05:00
self.previous_page = current_page - 1 if current_page > 1 else None
self.next_page = current_page + 1 if current_page < total_pages else None
2020-07-03 15:36:23 +08:00
self.start_page = None
self.end_page = None
self.page_range = None
self.has_prev = None
self.has_next = None
start_page = current_page - length // 2
end_page = current_page + length // 2
# decision is based on the start page and the end page
# both sides overflow
2023-01-11 19:11:31 -05:00
if (start_page < 1 and end_page > total_pages) or length >= total_pages:
2020-07-03 15:36:23 +08:00
self.start_page = 1
self.end_page = total_pages
self.has_prev = False
self.has_next = False
2023-01-11 19:11:31 -05:00
2020-07-03 15:36:23 +08:00
elif start_page < 1 and not end_page > total_pages:
self.start_page = 1
# this won't overflow because the total pages are more than the length
self.end_page = end_page - (start_page - 1)
self.has_prev = False
if end_page == total_pages:
self.has_next = False
else:
self.has_next = True
2023-01-11 19:11:31 -05:00
2020-07-03 15:36:23 +08:00
elif not start_page < 1 and end_page > total_pages:
self.end_page = total_pages
self.start_page = start_page - (end_page - total_pages)
self.has_next = False
if start_page == 1:
self.has_prev = False
else:
self.has_prev = True
# both sides do not overflow
elif not start_page < 1 and not end_page > total_pages:
self.start_page = start_page
self.end_page = end_page
self.has_prev = True
self.has_next = True
self.first_page = 1
self.last_page = total_pages
self.page_range = range(self.start_page, self.end_page + 1)
2020-10-03 23:27:41 +02:00
# assert self.has_prev is not None and self.has_next is not None
2021-08-01 12:36:03 +02:00
def GenerateDateUUIDMediaFilePath(instance, filename, path_root):
2023-01-11 19:11:31 -05:00
ext = filename.split(".")[-1]
2021-08-01 12:36:03 +02:00
filename = "%s.%s" % (uuid.uuid4(), ext)
2023-01-11 19:11:31 -05:00
root = ""
if path_root.endswith("/"):
2021-08-01 12:36:03 +02:00
root = path_root
else:
2023-01-11 19:11:31 -05:00
root = path_root + "/"
return root + timezone.now().strftime("%Y/%m/%d") + f"{filename}"