From fa6a6273c56c735314f82633e22dbec251ec01a7 Mon Sep 17 00:00:00 2001 From: Erfan Arefmehr Date: Tue, 26 Mar 2024 13:19:13 +0330 Subject: [PATCH] chore(pep8 & comments): remove unnecessary comments and reformat files to be pep8 friendly. --- api_v1/views.py | 36 +++++++++++++++-------------------- config/settings.py | 33 +++++--------------------------- config/urls.py | 23 +++------------------- content/admin.py | 1 + content/models.py | 1 - content/urls.py | 3 +-- content/views.py | 12 ++++-------- engagement/urls.py | 1 - relation/admin.py | 1 + relation/urls.py | 3 --- user/admin.py | 1 + user/models.py | 9 +++++---- user/urls.py | 1 - user/views.py | 5 +++-- utils/base_utils.py | 2 +- utils/rate_limiter_handler.py | 15 +++++++-------- utils/session_utils.py | 1 - 17 files changed, 47 insertions(+), 101 deletions(-) diff --git a/api_v1/views.py b/api_v1/views.py index a316f15..4962684 100644 --- a/api_v1/views.py +++ b/api_v1/views.py @@ -1,15 +1,15 @@ from django.http import JsonResponse from rest_framework.decorators import api_view, permission_classes -from rest_framework.permissions import IsAuthenticated from rest_framework.pagination import PageNumberPagination -from .serializers import UserSerialized, PostSerialized, FollowerListSerialized, FollowingListSerialized, TopicSerialized +from rest_framework.permissions import IsAuthenticated + from relation.models import Relation -from utils.base_utils import get_random_topics from user.models import User +from utils.base_utils import get_random_topics +from .serializers import UserSerialized, PostSerialized, FollowerListSerialized, FollowingListSerialized, \ + TopicSerialized - -# Create your views here. def index(request): return JsonResponse({'message': 'ZED API v1'}) @@ -17,54 +17,51 @@ def index(request): @api_view(['GET']) @permission_classes([IsAuthenticated]) def user_profile(request): - user = request.user user = UserSerialized(user) return JsonResponse(user.data, safe=False) - + @api_view(['GET']) @permission_classes([IsAuthenticated]) def user_posts(request): - user = request.user posts = user.posts.all().order_by('-created_time') paginator = PageNumberPagination() paginator.page_size = 10 paginated_posts = paginator.paginate_queryset(posts, request) - result = PostSerialized(paginated_posts, many=True) + result = PostSerialized(paginated_posts, many=True) return paginator.get_paginated_response(result.data) + @api_view(['GET']) @permission_classes([IsAuthenticated]) def user_followerlist(request): - user = request.user - + followers = Relation.objects.filter(following=user) - + followers = FollowerListSerialized(followers, many=True) - + return JsonResponse(followers.data, safe=False) @api_view(['GET']) @permission_classes([IsAuthenticated]) def user_followinglist(request): - user = request.user - + following = Relation.objects.filter(follower=user) - + following = FollowingListSerialized(following, many=True) - + return JsonResponse(following.data, safe=False) + @api_view(['GET']) @permission_classes([IsAuthenticated]) def user_suggestions(request): - current_user = request.user topics = get_random_topics() @@ -76,6 +73,3 @@ def user_suggestions(request): suggestions = UserSerialized(random_suggestions, many=True) return JsonResponse({'topics': serializedTopics.data, 'suggests': suggestions.data}, safe=False) - - - diff --git a/config/settings.py b/config/settings.py index 7ddbd2d..0a0df5f 100644 --- a/config/settings.py +++ b/config/settings.py @@ -1,25 +1,12 @@ -""" -Django settings for config project. - -Generated by 'django-admin startproject' using Django 5.0.3. - -For more information on this file, see -https://docs.djangoproject.com/en/5.0/topics/settings/ - -For the full list of settings and their values, see -https://docs.djangoproject.com/en/5.0/ref/settings/ -""" import os +from datetime import timedelta from pathlib import Path + from decouple import config -from datetime import timedelta + # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent - -# Quick-start development settings - unsuitable for production -# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ - # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY', False) @@ -42,7 +29,6 @@ 'debug_toolbar', ] - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', @@ -104,9 +90,7 @@ WSGI_APPLICATION = 'config.wsgi.application' - # Database -# https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { @@ -115,9 +99,7 @@ } } - # Password validation -# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { @@ -134,9 +116,7 @@ }, ] - # Internationalization -# https://docs.djangoproject.com/en/5.0/topics/i18n/ LANGUAGE_CODE = 'en-us' @@ -146,9 +126,7 @@ USE_TZ = True - # Static files (CSS, JavaScript, Images) -# https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) @@ -157,18 +135,17 @@ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Default primary key field type -# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', - 'rest_framework.authentication.SessionAuthentication', + 'rest_framework.authentication.SessionAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=30), -} \ No newline at end of file +} diff --git a/config/urls.py b/config/urls.py index 361db03..9f497ee 100644 --- a/config/urls.py +++ b/config/urls.py @@ -1,24 +1,7 @@ -""" -URL configuration for config project. - -The `urlpatterns` list routes URLs to views. For more information please see: - https://docs.djangoproject.com/en/5.0/topics/http/urls/ -Examples: -Function views - 1. Add an import: from my_app import views - 2. Add a URL to urlpatterns: path('', views.home, name='home') -Class-based views - 1. Add an import: from other_app.views import Home - 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') -Including another URLconf - 1. Import the include() function: from django.urls import include, path - 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) -""" -from django.contrib import admin -from django.urls import path, include from django.conf import settings from django.conf.urls.static import static - +from django.contrib import admin +from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), @@ -26,7 +9,7 @@ path('', include('engagement.urls')), path('', include('relation.urls')), path('', include('user.urls')), - path('api/v1/',include('api_v1.urls')), + path('api/v1/', include('api_v1.urls')), path('__debug__/', include('debug_toolbar.urls')), ] diff --git a/content/admin.py b/content/admin.py index 5024e4a..07153b4 100644 --- a/content/admin.py +++ b/content/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import Topic, Post, Comment, Repost admin.site.register(Topic) diff --git a/content/models.py b/content/models.py index af9236e..a215910 100644 --- a/content/models.py +++ b/content/models.py @@ -3,7 +3,6 @@ from django.contrib.auth import get_user_model from django.db import models -from django.db.models import Q from django.utils.translation import gettext_lazy as _ from utils.models import BaseModel diff --git a/content/urls.py b/content/urls.py index eceafe5..9ff03f4 100644 --- a/content/urls.py +++ b/content/urls.py @@ -2,7 +2,6 @@ from .views import * - app_name = 'content' urlpatterns = [ @@ -15,5 +14,5 @@ path('profile//', other_user_profile, name='other_user_profile'), path('settings/', settings, name='settings'), path('search//', search, name='search'), - path("unfollow//",ActionUnFollowView.as_view(),name="actionunfollow"), + path("unfollow//", ActionUnFollowView.as_view(), name="actionunfollow"), ] diff --git a/content/views.py b/content/views.py index 8343995..ee1eaba 100644 --- a/content/views.py +++ b/content/views.py @@ -1,3 +1,5 @@ +from urllib.parse import unquote + from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist @@ -7,13 +9,11 @@ from django.views import View from content.models import Post, Comment, Topic -from engagement.models import LikedPost, LikeNotification +from engagement.models import LikedPost from relation.models import Relation from utils.base_utils import left_nav_post_form_processing, mobile_post_form_processing, get_random_topics, \ get_random_follow_suggestions, toggle_like_post, toggle_like_comment, format_date from utils.session_utils import get_current_user -from urllib.parse import unquote - User = get_user_model() @@ -218,9 +218,6 @@ def profile(request): for post in posts: post.is_liked = LikedPost.objects.filter(post=post, liker=current_user).exists() - - - if request.POST.get('profile_post_comment_submit_btn'): current_post_id = request.POST.get('hidden_post_id') return HttpResponseRedirect('/post/' + str(current_post_id) + '/') @@ -242,7 +239,7 @@ def profile(request): 'posts_count': len(posts), 'followers_count': len(followers), 'followings_count': len(followings), - + } return render(request, 'profile/profile.html', data) @@ -270,7 +267,6 @@ def other_user_profile(request, other_user_username): for post in posts: post.is_liked = LikedPost.objects.filter(post=post, liker=current_user).exists() - follow_current_user = Relation.objects.filter( following=current_user, follower=other_user, diff --git a/engagement/urls.py b/engagement/urls.py index 66aa344..fda4a70 100644 --- a/engagement/urls.py +++ b/engagement/urls.py @@ -2,7 +2,6 @@ from .views import * - app_name = 'engagement' urlpatterns = [ diff --git a/relation/admin.py b/relation/admin.py index 76ba15e..308d0b1 100644 --- a/relation/admin.py +++ b/relation/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import Relation admin.site.register(Relation) diff --git a/relation/urls.py b/relation/urls.py index 01ffb55..61e6981 100644 --- a/relation/urls.py +++ b/relation/urls.py @@ -1,6 +1,3 @@ -from django.urls import path - - app_name = 'relation' urlpatterns = [ diff --git a/user/admin.py b/user/admin.py index c4a654c..c444238 100644 --- a/user/admin.py +++ b/user/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import User admin.site.register(User) diff --git a/user/models.py b/user/models.py index f31e336..3179d40 100644 --- a/user/models.py +++ b/user/models.py @@ -2,14 +2,15 @@ from django.contrib.auth.models import AbstractUser from django.db import models - from django.utils.translation import gettext_lazy as _ class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) - profile_photo = models.ImageField(verbose_name=_('user profile photo'), upload_to='profile_photos/', blank=True, null=True) - banner_photo = models.ImageField(verbose_name=_('user banner photo'), upload_to='banner_photos/', blank=True, null=True) + profile_photo = models.ImageField(verbose_name=_('user profile photo'), upload_to='profile_photos/', blank=True, + null=True) + banner_photo = models.ImageField(verbose_name=_('user banner photo'), upload_to='banner_photos/', blank=True, + null=True) bio = models.TextField(verbose_name=_('user bio'), null=True, blank=True) class Meta: @@ -22,5 +23,5 @@ def __str__(self): full_name = "%s %s" % (self.first_name, self.last_name) return full_name.strip() else: - username = "%s" % (self.username, ) + username = "%s" % (self.username,) return username.strip() diff --git a/user/urls.py b/user/urls.py index 361996b..53043e8 100644 --- a/user/urls.py +++ b/user/urls.py @@ -2,7 +2,6 @@ from .views import * - app_name = 'user' urlpatterns = [ diff --git a/user/views.py b/user/views.py index b5a2bcd..c65f3f4 100644 --- a/user/views.py +++ b/user/views.py @@ -1,6 +1,6 @@ -from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User +from django.shortcuts import render, redirect from django.views import View from .models import User @@ -22,7 +22,8 @@ def post(self, request): if User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists(): return render(request, self.template_name, {'credentials_taken': True}) - user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name, last_name=last_name) + user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name, + last_name=last_name) login(request, user) return redirect('/') diff --git a/utils/base_utils.py b/utils/base_utils.py index a084281..e67a1b9 100644 --- a/utils/base_utils.py +++ b/utils/base_utils.py @@ -79,4 +79,4 @@ def toggle_like_comment(current_user, current_comment): def format_date(date): - return date.strftime('%b %Y') \ No newline at end of file + return date.strftime('%b %Y') diff --git a/utils/rate_limiter_handler.py b/utils/rate_limiter_handler.py index 50cbbaf..7e15943 100644 --- a/utils/rate_limiter_handler.py +++ b/utils/rate_limiter_handler.py @@ -1,12 +1,11 @@ -from typing import Optional,List - +import json from datetime import datetime +from typing import Optional, List + from django.http.response import HttpResponse from .redis_manager import RedisHandler -import json - redis_context = RedisHandler("localhost", 6379, 0) redis_context.connect() @@ -24,7 +23,7 @@ class RateLimiterHandler: EACH_SECONDS: int = 60 @classmethod - def do_handler(cls,request,allowed_paths:Optional[List[str]] = None) -> None | HttpResponse: + def do_handler(cls, request, allowed_paths: Optional[List[str]] = None) -> None | HttpResponse: if (allowed_paths is not None) and (request.path not in allowed_paths): return None @@ -55,9 +54,9 @@ def do_handler(cls,request,allowed_paths:Optional[List[str]] = None) -> None | H redis_context.redis_client.delete(cls.USER_REQUEST_COUNT.format(client_ip)) redis_context.redis_client.delete(cls.USER_LAST_REQUEST_TIME.format(client_ip)) else: - redis_context.redis_client.set(cls.USER_INFO_KEY.format(client_ip),client_ip) - redis_context.redis_client.set(cls.USER_REQUEST_COUNT.format(client_ip),0) - redis_context.redis_client.set(cls.USER_LAST_REQUEST_TIME.format(client_ip),str(datetime.now())) + redis_context.redis_client.set(cls.USER_INFO_KEY.format(client_ip), client_ip) + redis_context.redis_client.set(cls.USER_REQUEST_COUNT.format(client_ip), 0) + redis_context.redis_client.set(cls.USER_LAST_REQUEST_TIME.format(client_ip), str(datetime.now())) except ConnectionError: ... diff --git a/utils/session_utils.py b/utils/session_utils.py index ec35ccd..d88f067 100644 --- a/utils/session_utils.py +++ b/utils/session_utils.py @@ -1,5 +1,4 @@ from django.contrib.auth import get_user_model -from django.core.exceptions import ObjectDoesNotExist User = get_user_model()