Skip to content

Commit

Permalink
Merge pull request #54 from Packan1337/master
Browse files Browse the repository at this point in the history
added type hints to functions and methods
  • Loading branch information
israelias authored Sep 2, 2023
2 parents 115f35d + 156dc4c commit dcb24ac
Show file tree
Hide file tree
Showing 16 changed files with 107 additions and 107 deletions.
2 changes: 1 addition & 1 deletion backend/account/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


@receiver(post_save, sender=User)
def create_or_update_vendor(sender, instance, created, **kwargs):
def create_or_update_vendor(sender, instance, created, **kwargs) -> None:
print("RECEIVER")
print("SENDER", sender.username)
print("INSTANCE", instance)
Expand Down
2 changes: 1 addition & 1 deletion backend/account/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Query(graphene.ObjectType):
user_details = graphene.Field(UserType)
# user_details = graphene.List(UserType)

def resolve_user_details(root, info, **kwargs):
def resolve_user_details(root, info, **kwargs) -> User:
"""
The resolve_user_details function is a resolver function that returns the user details of the currently logged in user.
It takes three arguments: root, info, and **kwargs. The root argument is required by all resolve functions and contains data about the query itself;
Expand Down
14 changes: 7 additions & 7 deletions backend/account/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Meta:
fields = ["id", "username", "email", "password"]
extra_kwargs = {"password": {"write_only": True}}

def create(self, validated_data):
def create(self, validated_data: dict) -> User:
print("SERIALIZER")
user = User.objects.create_user(
validated_data["username"],
Expand All @@ -42,13 +42,13 @@ class Meta:
model = User
fields = ("old_password", "password")

def validate_old_password(self, value):
def validate_old_password(self, value: str) -> str:
user = self.context["request"].user
if not user.check_password(value):
raise serializers.ValidationError({"old_password": "Old password is not correct"})
return value

def update(self, instance, validated_data):
def update(self, instance, validated_data: dict) -> User:
user = self.context["request"].user

if user.id != instance.id:
Expand All @@ -71,19 +71,19 @@ class Meta:
"last_name": {"required": True},
}

def validate_email(self, value):
def validate_email(self, value: str) -> str:
user = self.context["request"].user
if User.objects.exclude(id=user.id).filter(email=value).exists():
raise serializers.ValidationError({"email": "This email is already in use."})
return value

def validate_username(self, value):
def validate_username(self, value: str) -> str:
user = self.context["request"].user
if User.objects.exclude(id=user.id).filter(username=value).exists():
raise serializers.ValidationError({"username": "This username is already in use."})
return value

def update(self, instance, validated_data):
def update(self, instance, validated_data: dict) -> User:
user = self.context["request"].user

if user.id != instance.id:
Expand All @@ -105,7 +105,7 @@ class AccountLoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()

def validate(self, data):
def validate(self, data: dict) -> dict:
user = authenticate(**data)
if user and user.is_active:
return user
Expand Down
8 changes: 4 additions & 4 deletions backend/account/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class AccountRegisterDetailView(generics.GenericAPIView):
permission_classes = (AllowAny,)

@swagger_auto_schema(responses={200: user_response})
def post(self, request, *args, **kwargs):
def post(self, request, *args, **kwargs) -> Response:

serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
Expand All @@ -75,7 +75,7 @@ class AccountLoginDetailView(generics.GenericAPIView):
permission_classes = (AllowAny,)

@swagger_auto_schema(responses={200: user_response})
def post(self, request, *args, **kwargs):
def post(self, request, *args, **kwargs) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
Expand Down Expand Up @@ -122,7 +122,7 @@ class AccountLogoutView(views.APIView):

permission_classes = (IsAuthenticated,)

def post(self, request):
def post(self, request) -> Response:

try:

Expand Down Expand Up @@ -158,7 +158,7 @@ class AccountLogoutAllView(views.APIView):

permission_classes = (IsAuthenticated,)

def post(self, request):
def post(self, request) -> Response:
try:
tokens = OutstandingToken.objects.filter(user_id=request.user.id)
for token in tokens:
Expand Down
2 changes: 1 addition & 1 deletion backend/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys


def main():
def main() -> None:
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
try:
Expand Down
16 changes: 8 additions & 8 deletions backend/order/cart.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from store.models import Product

class Cart(object):
def __init__(self, request):
def __init__(self, request: object) -> None:
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)

Expand All @@ -12,7 +12,7 @@ def __init__(self, request):

self.cart = cart

def __iter__(self):
def __iter__(self) -> None:
for p in self.cart.keys():
self.cart[str(p)]['product'] = Product.objects.get(pk=p)

Expand All @@ -21,10 +21,10 @@ def __iter__(self):

yield item

def __len__(self):
def __len__(self) -> int:
return sum(item['quantity'] for item in self.cart.values())

def add(self, product_id, quantity=1, update_quantity=False):
def add(self, product_id, quantity=1, update_quantity=False) -> None:
product_id = str(product_id)

if product_id not in self.cart:
Expand All @@ -38,20 +38,20 @@ def add(self, product_id, quantity=1, update_quantity=False):

self.save()

def remove(self, product_id):
def remove(self, product_id) -> None:
if product_id in self.cart:
del self.cart[product_id]
self.save()

def save(self):
def save(self) -> None:
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True

def clear(self):
def clear(self) -> None:
del self.session[settings.CART_SESSION_ID]
self.session.modified = True

def get_total_cost(self):
def get_total_cost(self) -> float:
for p in self.cart.keys():
self.cart[str(p)]['product'] = Product.objects.get(pk=p)

Expand Down
14 changes: 7 additions & 7 deletions backend/order/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Meta:
verbose_name = _("Order")
verbose_name_plural = _("Orders")

def save(self, *args, **kwargs):
def save(self, *args, **kwargs) -> None:
"""
If the Order instance is an immediate purchase and not an offer,
set the amount to be the price of the product.
Expand All @@ -62,13 +62,13 @@ def save(self, *args, **kwargs):

super(Order, self).save(*args, **kwargs)

def get_price(self):
def get_price(self) -> float:
return self.product.price

def get_absolute_url(self):
def get_absolute_url(self) -> str:
return reverse("order:order_list", args=[self.id])

def __str__(self):
def __str__(self) -> str:
return f"Product {self.product.title} ordered by {self.buyer.name}"


Expand All @@ -95,15 +95,15 @@ class Meta:
verbose_name = _("Order Detail")
verbose_name_plural = _("Order Details")

def get_absolute_url(self):
def get_absolute_url(self) -> str:
return reverse("orderdetails:orderdetails_list", args=[self.id])

def __str__(self):
def __str__(self) -> str:
return f"Order Details of {self.full_name} on order {self.order.id}"


@receiver(pre_delete, sender=Order)
def reset_product_is_available(sender, instance, **kwargs):
def reset_product_is_available(sender, instance, **kwargs) -> None:
"""
Reset an product's availability if an order for that product is deleted.
Expand Down
6 changes: 3 additions & 3 deletions backend/order/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class Meta:
}
extra_kwargs = {"amount": {"required": False}, "order_detail": {"required": False}}

def validate(self, data):
def validate(self, data: dict) -> dict:
"""
Check if product is avaialable or if it is already in the buyer's orders.
Ensure an offer is never more than the price of the product.
Expand Down Expand Up @@ -112,7 +112,7 @@ def validate(self, data):

return data

def create(self, validated_data):
def create(self, validated_data: dict) -> Order:
request = self.context["request"]
buyer = request.user.vendor
# buyer = Vendor.objects.get(created_by=request.user.vendor)
Expand All @@ -138,7 +138,7 @@ def create(self, validated_data):

return instance

def update(self, instance, validated_data):
def update(self, instance, validated_data: dict) -> Order:

user = self.context["request"].user.vendor

Expand Down
2 changes: 1 addition & 1 deletion backend/order/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class OrderItemCheckout(generics.CreateAPIView):
Checkout POST.
"""

def post(self, request, *args, **kwargs):
def post(self, request, *args, **kwargs) -> Response:
body = request.POST.get("body")
order_item = OrderModel.objects.create(
product=body["product"],
Expand Down
34 changes: 17 additions & 17 deletions backend/store/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
)


def upload_path(instance, filename):
def upload_path(instance, filename: str) -> str:
return "/".join(["images", str(instance.name), filename])


def rand_slug():
def rand_slug() -> str:
return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(6))


Expand Down Expand Up @@ -54,15 +54,15 @@ class Meta:
verbose_name = _("Category")
verbose_name_plural = _("Categories")

def get_absolute_url(self):
def get_absolute_url(self) -> str:
return reverse("store:category_list", args=[self.slug])

def save(self, *args, **kwargs):
def save(self, *args, **kwargs) -> None:
if not self.slug:
self.slug = slugify(rand_slug() + "-" + self.name)
super(Category, self).save(*args, **kwargs)

def get_slug_list(self):
def get_slug_list(self) -> list:
try:
ancestors = self.get_ancestors(include_self=True)
except:
Expand Down Expand Up @@ -129,20 +129,20 @@ class Meta:
verbose_name = _("Product")
verbose_name_plural = _("Products")

def get_absolute_url(self):
def get_absolute_url(self) -> str:
return reverse("store:product-detail", args=[self.slug])

def save(self, *args, **kwargs):
def save(self, *args, **kwargs) -> None:

if not self.slug:
self.slug = slugify(self.title)

super(Product, self).save(*args, **kwargs)

def __str__(self):
def __str__(self) -> str:
return self.title

def __unicode__(self):
def __unicode__(self) -> str:
return self.title


Expand Down Expand Up @@ -185,23 +185,23 @@ class Meta:
verbose_name_plural = _("Versatile Images")
UniqueConstraint(fields=["is_feature"], condition=Q(is_feature=True), name="is_feature_is_unique")

def get_thumbnail(self):
def get_thumbnail(self) -> str:
if self.image:
thumbnail = self.make_thumbnail(self.image)
return thumbnail
else:
return "https://via.placeholder.com/240x180.jpg"

def make_thumbnail(self, image, size=("240x180")):
def make_thumbnail(self, image, size=("240x180")) -> str:
return image.thumbnail[size].url

def __str__(self):
def __str__(self) -> str:
return self.name

def __unicode__(self):
def __unicode__(self) -> str:
return self.name

def save(self, *args, **kwargs):
def save(self, *args, **kwargs) -> None:
if not self.name:
if self.is_feature:
self.name = self.product.title + "-" + "feature" + "-" + rand_slug()
Expand All @@ -215,7 +215,7 @@ def save(self, *args, **kwargs):


@receiver(post_save, sender=Image)
def warm_image_instances_post_save(sender, instance, **kwargs):
def warm_image_instances_post_save(sender, instance, **kwargs) -> None:
"""Ensures Image objects are created post-save"""
all_img_warmer = VersatileImageFieldWarmer(
instance_or_queryset=instance, rendition_key_set="default_product", image_attr="image", verbose=True
Expand All @@ -233,12 +233,12 @@ class Meta:
verbose_name = _("Favorite Product")
verbose_name_plural = _("Favorite Products")

def __str__(self):
def __str__(self) -> str:
return "%s's favorites" % self.vendor.name


@receiver(pre_delete, sender=Product)
def delete_category_if_null(sender, instance, **kwargs):
def delete_category_if_null(sender, instance, **kwargs) -> None:
"""
Delete category objects if it has no other related products.
Expand Down
Loading

3 comments on commit dcb24ac

@vercel
Copy link

@vercel vercel bot commented on dcb24ac Sep 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on dcb24ac Sep 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on dcb24ac Sep 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.