Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mypy type errors fix #324

Merged
merged 20 commits into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion backend/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Iterable, Any

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

Expand Down Expand Up @@ -73,7 +75,7 @@ class EmailSendStatusAdmin(admin.ModelAdmin):
admin.site.register(EmailSendStatus, EmailSendStatusAdmin)

# admin.site.unregister(User)
fields = list(UserAdmin.fieldsets)
fields = list(UserAdmin.fieldsets) # type: ignore[arg-type]
fields[0] = (None, {"fields": ("username", "password", "logged_in_as_team", "awaiting_email_verification")})
UserAdmin.fieldsets = tuple(fields)
admin.site.register(User, UserAdmin)
Expand Down
9 changes: 3 additions & 6 deletions backend/api/healthcheck/healthcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ def ping(request: HttpRequest) -> HttpResponse:
@login_not_required
def healthcheck(request: HttpRequest) -> HttpResponse:
try:
status = connection.ensure_connection()
except OperationalError:
status = "error"

if not status: # good
connection.ensure_connection()
return HttpResponse(status=200, content="All operations are up and running!")
return HttpResponse(status=503, content="Service Unavailable")
except OperationalError:
return HttpResponse(status=503, content="Service Unavailable")
6 changes: 3 additions & 3 deletions backend/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def get_item(name: str, url_name: Optional[str] = None, icon: Optional[str] = No
"icon": icon,
}

def generate_breadcrumbs(*breadcrumb_list: str) -> List[Dict[str, Any]]:
def generate_breadcrumbs(*breadcrumb_list: str) -> List[dict[Any, Any] | None]:
"""
Generate a list of breadcrumb items based on the provided list of breadcrumb names.

Expand All @@ -64,7 +64,7 @@ def generate_breadcrumbs(*breadcrumb_list: str) -> List[Dict[str, Any]]:
"""
return [all_items.get(breadcrumb) for breadcrumb in breadcrumb_list]

current_url_name: str = request.resolver_match.url_name
current_url_name: str | Any = request.resolver_match.url_name # type: ignore[union-attr]

all_items: Dict[str, dict] = {
"dashboard": get_item("Dashboard", "dashboard", "house"),
Expand All @@ -78,7 +78,7 @@ def generate_breadcrumbs(*breadcrumb_list: str) -> List[Dict[str, Any]]:
"clients create": get_item("Create", "clients create"),
}

all_breadcrumbs: Dict[str, list] = {
all_breadcrumbs: Dict[str | None, list] = {
"dashboard": generate_breadcrumbs("dashboard"),
"user settings teams": generate_breadcrumbs("dashboard", "user settings teams"),
"receipts dashboard": generate_breadcrumbs("dashboard", "receipts dashboard"),
Expand Down
2 changes: 1 addition & 1 deletion backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def get_queryset(self):


class User(AbstractUser):
objects = CustomUserManager()
objects = CustomUserManager() # type: ignore

logged_in_as_team = models.ForeignKey("Team", on_delete=models.SET_NULL, null=True, blank=True)
awaiting_email_verification = models.BooleanField(default=True)
Expand Down
2 changes: 1 addition & 1 deletion backend/types/emails.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Literal, Optional, List, TypedDict, Dict
from typing import Literal, TypedDict

from mypy_boto3_sesv2.type_defs import SendEmailResponseTypeDef, SendBulkEmailResponseTypeDef, BulkEmailEntryResultTypeDef

Expand Down
2 changes: 0 additions & 2 deletions backend/views/core/currency_converter/dashboard.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import datetime

from django.http import HttpRequest
from django.shortcuts import render
from forex_python.converter import CurrencyRates
Expand Down
8 changes: 4 additions & 4 deletions backend/views/core/invoices/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def edit_invoice(request: HttpRequest, invoice_id):
except Invoice.DoesNotExist:
return JsonResponse({"message": "Invoice not found"}, status=404)

if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization:
if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization: # type: ignore[union-attr]
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
Expand All @@ -83,7 +83,7 @@ def edit_invoice(request: HttpRequest, invoice_id):
)

attributes_to_updates = {
"date_due": datetime.strptime(request.POST.get("date_due"), "%Y-%m-%d").date(),
"date_due": datetime.strptime(request.POST.get("date_due"), "%Y-%m-%d").date(), # type: ignore[arg-type]
"date_issued": request.POST.get("date_issued"),
"self_name": request.POST.get("from_name"),
"self_company": request.POST.get("from_company"),
Expand All @@ -102,7 +102,7 @@ def edit_invoice(request: HttpRequest, invoice_id):

client_to_id = request.POST.get("selected_client")
try:
client_to_obj = Client.objects.get(id=client_to_id, user=request.user)
client_to_obj = Client.objects.get(id=client_to_id, user=request.user) # type: ignore[misc]
except (Client.DoesNotExist, ValueError):
client_to_obj = None

Expand Down Expand Up @@ -140,7 +140,7 @@ def edit_invoice(request: HttpRequest, invoice_id):

messages.success(request, "Invoice edited")

if request.htmx:
if request.htmx: # type: ignore[attr-defined]
return render(request, "base/toasts.html")

return invoice_edit_page_get(request, invoice_id)
Expand Down
6 changes: 4 additions & 2 deletions backend/views/core/settings/teams.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Optional

from django.db.models import When, Case, BooleanField
from django.http import HttpRequest
from django.shortcuts import render
Expand All @@ -6,8 +8,8 @@


def teams_dashboard(request: HttpRequest):
request.user: User = request.user
users_team: Optional[Team] = request.user.logged_in_as_team
request.user: User = request.user # type: ignore[misc]
users_team: Optional[Team] = request.user.logged_in_as_team # type: ignore[union-attr, assignment]

if not users_team:
user_with_counts = User.objects.prefetch_related("teams_joined", "teams_leader_of").get(pk=request.user.pk)
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ module = [
"forex_python.converter",
"login_required",
"storages.backends.s3",
"social_django.models"
"social_django.models",
"emails",
"step_functions",
TreyWW marked this conversation as resolved.
Show resolved Hide resolved
"django_components"
]
ignore_missing_imports = true
23 changes: 8 additions & 15 deletions settings/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@
import json
import os
import sys
from dataclasses import dataclass
from logging import exception
from typing import Literal, List

from collections.abc import Sequence
from typing import Optional

import boto3
import environ
Expand Down Expand Up @@ -105,7 +100,7 @@ def send_email(data: SingleEmailInput) -> SingleEmailSuccessResponse | SingleEma

try:
if isinstance(data.content, dict):
data_str: str = (
data_str = (
data.content.get("template_data")
if isinstance(data.content.get("template_data"), str)
else json.dumps(data.content.get("template_data"))
Expand All @@ -114,21 +109,21 @@ def send_email(data: SingleEmailInput) -> SingleEmailSuccessResponse | SingleEma
from_email_address: str = str(data.from_address_name_prefix) if data.from_address_name_prefix else ""
from_email_address += str(data.from_address or get_var("AWS_SES_FROM_ADDRESS"))

response: SendEmailResponseTypeDef = EMAIL_CLIENT.send_email(
response = EMAIL_CLIENT.send_email(
FromEmailAddress=from_email_address,
Destination={"ToAddresses": data.destination},
Content={"Template": {"TemplateName": data.content.get("template_name"), "TemplateData": data_str}},
Content={"Template": {"TemplateName": data.content.get("template_name"), "TemplateData": data_str}}, # type: ignore
ConfigurationSetName=data.ConfigurationSetName or "",
)
else:
from_email_address: str = str(data.from_address_name_prefix) if data.from_address_name_prefix else ""
from_email_address = str(data.from_address_name_prefix) if data.from_address_name_prefix else ""
from_email_address += str(data.from_address or get_var("AWS_SES_FROM_ADDRESS"))

response: SendEmailResponseTypeDef = EMAIL_CLIENT.send_email(
response = EMAIL_CLIENT.send_email(
FromEmailAddress=from_email_address,
Destination={"ToAddresses": data.destination},
Content={"Simple": {"Subject": {"Data": data.subject}, "Body": {"Text": {"Data": data.content}}}},
ConfigurationSetName=data.ConfigurationSetName,
ConfigurationSetName=data.ConfigurationSetName or "",
)
return SingleEmailSuccessResponse(response)
except EMAIL_CLIENT.exceptions.MessageRejected:
Expand All @@ -152,7 +147,7 @@ def send_templated_bulk_email(data: BulkTemplatedEmailInput) -> BulkEmailSuccess
for entry in data.email_list:
destination: list[str] = [entry.destination] if not isinstance(entry.destination, list) else entry.destination

data_str = entry.template_data if isinstance(entry.template_data, str) else json.dumps(entry.template_data)
data_str: str = entry.template_data if isinstance(entry.template_data, str) else json.dumps(entry.template_data)

entries.append(
{
Expand All @@ -162,9 +157,7 @@ def send_templated_bulk_email(data: BulkTemplatedEmailInput) -> BulkEmailSuccess
)

try:
data_str: str = (
data.default_template_data if isinstance(data.default_template_data, str) else json.dumps(data.default_template_data)
)
data_str = data.default_template_data if isinstance(data.default_template_data, str) else json.dumps(data.default_template_data)
from_email_address: str = str(data.from_address_name_prefix) if data.from_address_name_prefix else ""
from_email_address += str(data.from_address or get_var("AWS_SES_FROM_ADDRESS"))

Expand Down
5 changes: 2 additions & 3 deletions settings/local_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
DB_TYPE = "mysql" if DB_TYPE in ["mysql", "mariadb"] else DB_TYPE

if DB_TYPE == "mysql" or DB_TYPE == "postgres":
DATABASES = {
DATABASES: dict = {
"default": {
"ENGINE": (
"django.db.backends.postgresql_psycopg2"
Expand Down Expand Up @@ -45,8 +45,7 @@
}
print("[BACKEND] Using sqlite3 database", flush=True)


ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
ALLOWED_HOSTS: list[str | None] = ["localhost", "127.0.0.1"]
Domejko marked this conversation as resolved.
Show resolved Hide resolved

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = (
"1" # THIS WILL ALLOW HTTP - NOT RECOMMENDED
Expand Down
2 changes: 1 addition & 1 deletion settings/prod_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,6 @@
print(f"[BACKEND] Using {DB_TYPE} database: {os.environ.get('DATABASE_NAME')}")


ALLOWED_HOSTS = [os.environ.get("URL")]
ALLOWED_HOSTS: list[str | None] = [os.environ.get("URL")]
TreyWW marked this conversation as resolved.
Show resolved Hide resolved

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "0" # THIS WILL ALLOW HTTP IF IT'S SET TO 1 - NOT RECOMMENDED
8 changes: 4 additions & 4 deletions settings/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pathlib import Path

from django.contrib.messages import constants as messages
from django.contrib.staticfiles.storage import FileSystemStorage
from django.contrib.staticfiles.storage import FileSystemStorage # type: ignore
from storages.backends.s3 import S3Storage

from .helpers import get_var
Expand Down Expand Up @@ -91,7 +91,7 @@

BASE_DIR = Path(__file__).resolve().parent.parent

EMAIL_WHITELIST = []
EMAIL_WHITELIST: list[str] = []
AUTHENTICATION_BACKENDS = [
# "django.contrib.auth.backends.ModelBackend",
"backend.auth_backends.EmailInsteadOfUsernameBackend",
Expand Down Expand Up @@ -349,7 +349,7 @@ class CustomPrivateMediaStorage(S3Storage):
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"

class CustomPublicMediaStorage(FileSystemStorage): # This overrides the AWS version
class CustomPublicMediaStorage(FileSystemStorage): # type: ignore # This overrides the AWS version
...


Expand All @@ -359,7 +359,7 @@ class CustomPublicMediaStorage(FileSystemStorage): # This overrides the AWS ver
PRIVATE_FILE_STORAGE = "settings.settings.CustomPrivateMediaStorage"
else:

class CustomPrivateMediaStorage(FileSystemStorage): # This overrides the AWS version
class CustomPrivateMediaStorage(FileSystemStorage): # type: ignore # This overrides the AWS version
...

PRIVATE_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"
Expand Down