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: fix mypy errors in wladmin module. Rel: #3703 #12690

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion weblate/billing/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@
projects = models.ManyToManyField(
Project, blank=True, verbose_name=gettext_lazy("Billed projects")
)
owners = models.ManyToManyField(

Check failure on line 161 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

Need type annotation for "owners"
User, blank=True, verbose_name=gettext_lazy("Billing owners")
)
state = models.IntegerField(
Expand Down Expand Up @@ -193,7 +193,7 @@
# with payment processor
payment = models.JSONField(editable=False, default=dict, encoder=DjangoJSONEncoder)

objects = BillingManager.from_queryset(BillingQuerySet)()
objects: BillingQuerySet = BillingManager.from_queryset(BillingQuerySet)()

Check failure on line 196 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

Incompatible types in assignment (expression has type "BillingManager", variable has type "BillingQuerySet")
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh, I'd overlooked this one. I've tried to investigate a bit but couldn't find a working solution, just this issue ticket typeddjango/django-stubs#1067 or #type: ignore[assignment] or using cast (which seems too brutal)

Should I remove this change?

Copy link
Member

Choose a reason for hiding this comment

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

Probably yes. I think this is best to be addressed at django-stubs or mypy, otherwise we end up doing that on every model.

Copy link
Member

Choose a reason for hiding this comment

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

Furthermore, this does address only accessing query set via .objects but not when using related manager.


class Meta:
verbose_name = "Customer billing"
Expand All @@ -201,7 +201,7 @@

def __str__(self) -> str:
projects = self.projects_display
owners = self.owners.order()

Check failure on line 204 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

"ManyRelatedManager[User, Any]" has no attribute "order"
if projects:
base = projects
elif owners:
Expand Down Expand Up @@ -356,7 +356,7 @@
@admin.display(description=gettext_lazy("Last invoice"))
def last_invoice(self):
try:
invoice = self.invoice_set.order_by("-start")[0]

Check failure on line 359 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

"Billing" has no attribute "invoice_set"
except IndexError:
return gettext("N/A")
return f"{invoice.start} - {invoice.end}"
Expand Down Expand Up @@ -397,10 +397,10 @@
"""
end = timezone.now()
if not now:
end -= timedelta(days=settings.BILLING_GRACE_PERIOD)

Check failure on line 400 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

'Settings' object has no attribute 'BILLING_GRACE_PERIOD'
return (
(self.plan.is_free and self.state == Billing.STATE_ACTIVE)
or self.invoice_set.filter(end__gte=end).exists()

Check failure on line 403 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

"Billing" has no attribute "invoice_set"
or self.state == Billing.STATE_TRIAL
)

Expand All @@ -413,7 +413,7 @@
if self.check_expiry():
self.expiry = None
self.removal = timezone.now() + timedelta(
days=settings.BILLING_REMOVAL_PERIOD

Check failure on line 416 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

'Settings' object has no attribute 'BILLING_REMOVAL_PERIOD'
)
modified = True

Expand Down Expand Up @@ -543,7 +543,7 @@
verbose_name_plural = "Invoices"

def __str__(self) -> str:
return f"{self.start} - {self.end}: {self.billing if self.billing_id else None}"

Check failure on line 546 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

"Invoice" has no attribute "billing_id"; maybe "billing"?

@cached_property
def filename(self) -> str | None:
Expand All @@ -566,7 +566,7 @@
if self.end <= self.start:
raise ValidationError("Start has be to before end!")

if not self.billing_id:

Check failure on line 569 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

"Invoice" has no attribute "billing_id"; maybe "billing"?
return

overlapping = Invoice.objects.filter(
Expand Down Expand Up @@ -609,7 +609,7 @@
instance = instance.project
# Collect billings to update for delete_project_bill
instance.billings_to_update = list(
instance.billing_set.values_list("pk", flat=True)

Check failure on line 612 in weblate/billing/models.py

View workflow job for this annotation

GitHub Actions / mypy

"Project" has no attribute "billing_set"
)


Expand Down
4 changes: 2 additions & 2 deletions weblate/wladmin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,12 @@

def get_support_status(request: AuthenticatedHttpRequest) -> SupportStatusDict:
if hasattr(request, "weblate_support_status"):
support_status = request.weblate_support_status
support_status: SupportStatusDict = request.weblate_support_status

Check warning on line 331 in weblate/wladmin/models.py

View check run for this annotation

Codecov / codecov/patch

weblate/wladmin/models.py#L331

Added line #L331 was not covered by tests
else:
support_status = cache.get(SUPPORT_STATUS_CACHE_KEY)
if support_status is None:
support_status_instance = SupportStatus.objects.get_current()
support_status: SupportStatusDict = {
support_status = {
"has_support": support_status_instance.name != "community",
"in_limits": support_status_instance.in_limits,
}
Expand Down
4 changes: 2 additions & 2 deletions weblate/wladmin/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from django.utils.translation import gettext, gettext_lazy

if TYPE_CHECKING:
from weblate.auth.models import AuthenticatedHttpRequest
from django.http import HttpRequest
Copy link
Member

Choose a reason for hiding this comment

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

The intention here is that Django's HttpRequest can have AnonymousUser what can't happen in Weblate. That's why AuthenticatedHttpRequest was introduced. Without that each access to reuqest.user has complains from mypy.

Copy link
Member

Choose a reason for hiding this comment

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



class WeblateAdminSite(AdminSite):
Expand All @@ -38,7 +38,7 @@ def site_url(self):
return settings.URL_PREFIX
return "/"

def each_context(self, request: AuthenticatedHttpRequest):
def each_context(self, request: HttpRequest):
from weblate.wladmin.models import ConfigurationError

result = super().each_context(request)
Expand Down
17 changes: 9 additions & 8 deletions weblate/wladmin/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from weblate.utils.version import GIT_LINK, GIT_REVISION
from weblate.utils.views import show_form_errors
from weblate.vcs.ssh import (
KeyType,
add_host_key,
can_generate_key,
generate_ssh_key,
Expand Down Expand Up @@ -322,9 +323,8 @@ def performance(request: AuthenticatedHttpRequest) -> HttpResponse:

@management_access
def ssh_key(request: AuthenticatedHttpRequest) -> HttpResponse:
filename, data = get_key_data_raw(
key_type=request.GET.get("type", "rsa"), kind="private"
)
key_type = cast(KeyType, request.GET.get("type", "rsa"))
filename, data = get_key_data_raw(key_type=key_type, kind="private")
if data is None:
raise Http404

Expand All @@ -345,7 +345,8 @@ def ssh(request: AuthenticatedHttpRequest) -> HttpResponse:

# Generate key if it does not exist yet
if can_generate and action == "generate":
generate_ssh_key(request, key_type=request.POST.get("type", "rsa"))
key_type = cast(KeyType, request.POST.get("type", "rsa"))
generate_ssh_key(request, key_type=key_type)
return redirect("manage-ssh")

# Read key data if it exists
Expand Down Expand Up @@ -429,14 +430,14 @@ def users_check(request: AuthenticatedHttpRequest) -> HttpResponse:
# Legacy links for care.weblate.org integration
if "email" in data and "q" not in data:
data = data.copy()
data["q"] = data["email"]
data.setlist("q", data.getlist("email"))
form = AdminUserSearchForm(data)

user_list = None
if form.is_valid():
user_list = User.objects.search(
form.cleaned_data.get("q", ""), parser=form.fields["q"].parser
)[:2]
parser = getattr(form.fields["q"], "parser", "unit")
query = form.cleaned_data.get("q", "")
user_list = User.objects.search(query, parser=parser)[:2]
if user_list.count() != 1:
return redirect_param(
"manage-users", "?q={}".format(quote(form.cleaned_data["q"]))
Expand Down
Loading