Skip to content

chore: apply more ruff fixes #710

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

Merged
merged 1 commit into from
May 26, 2025
Merged
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 .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.11.11
hooks:
- id: ruff
- id: ruff-check
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format
- repo: meta
Expand Down
Empty file modified manage.py
100644 → 100755
Empty file.
23 changes: 20 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,32 @@ exclude = [
"site"
]
line-length = 120
output-format = "github"

[tool.ruff.lint]
ignore = []
select = ["E", "F", "I", "PLC", "PLE", "UP"]
ignore = [
"ANN", # TODO: Missing type annotations
"ARG001", # TODO: Unused function argument (mostly for API compatibility)
"ARG002", # TODO: Unused method argument (mostly for API compatibility)
"B026", # TODO: Star-arg unpacking after a keyword argument is strongly discouraged
"COM812", # CONFIG: incompatible with formatter
"D", # TODO: Missing documentation
"D203", # CONFIG: incompatible with D211
"D212", # CONFIG: incompatible with D213
"DJ008", # TODO: Model does not define `__str__` method
"FBT002", # TODO: Boolean default positional argument in function definition
"FBT003", # TODO: Boolean positional value in function call
"PT", # CONFIG: Not using pytest
"RUF012" # TODO: ClassVar type annotations
]
select = ["ALL"]

[tool.ruff.lint.mccabe]
max-complexity = 10

[tool.ruff.lint.per-file-ignores]
"social_django/migrations/*.py" = ["RUF012"]
"tests/settings.py" = ["PTH"]

[tool.setuptools]
packages = ["social_django"]

Expand Down
2 changes: 1 addition & 1 deletion social_django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ def fake_init(self, strategy=None, *args, **kwargs):

if not getattr(BaseAuth, "__init_patched", False):
BaseAuth.__init__ = baseauth_init_workaround(BaseAuth.__init__) # type: ignore[method-assign]
BaseAuth.__init_patched = True # type: ignore[attr-defined]
BaseAuth.__init_patched = True # type: ignore[attr-defined] # noqa: SLF001
8 changes: 5 additions & 3 deletions social_django/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ class UserSocialAuthOption(admin.ModelAdmin):
def get_search_fields(self, request=None):
search_fields = getattr(settings, setting_name("ADMIN_USER_SEARCH_FIELDS"), None)
if search_fields is None:
_User = UserSocialAuth.user_model()
username = getattr(_User, "USERNAME_FIELD", None) or hasattr(_User, "username") and "username" or None
_User = UserSocialAuth.user_model() # noqa: N806
username = getattr(_User, "USERNAME_FIELD", None) or (hasattr(_User, "username") and "username") or None
fieldnames = ("first_name", "last_name", "email", username)
all_names = self._get_all_field_names(_User._meta)
all_names = self._get_all_field_names(
_User._meta # noqa: SLF001
)
search_fields = [name for name in fieldnames if name and name in all_names]
return ["user__" + name for name in search_fields] + getattr(settings, setting_name("ADMIN_SEARCH_FIELDS"), [])

Expand Down
10 changes: 6 additions & 4 deletions social_django/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,18 @@ def __setitem__(self, name, value):


def backends(request):
"""Load Social Auth current user data to context under the key 'backends'.
Will return the output of social_core.backends.utils.user_backends_data."""
"""
Load Social Auth current user data to context under the key 'backends'.
Will return the output of social_core.backends.utils.user_backends_data.
"""
return {"backends": LazyDict(lambda: user_backends_data(request.user, settings.AUTHENTICATION_BACKENDS, Storage))}


def login_redirect(request):
"""Load current redirect to context."""
try:
value = (
request.method == "POST" and request.POST.get(REDIRECT_FIELD_NAME) or request.GET.get(REDIRECT_FIELD_NAME)
value = (request.method == "POST" and request.POST.get(REDIRECT_FIELD_NAME)) or request.GET.get(
REDIRECT_FIELD_NAME
)
except MultiPartParserError:
# request POST may be malformed
Expand Down
5 changes: 1 addition & 4 deletions social_django/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@

POSTGRES_JSONFIELD = getattr(settings, setting_name("POSTGRES_JSONFIELD"), False)

if POSTGRES_JSONFIELD:
JSONFIELD_ENABLED = True
else:
JSONFIELD_ENABLED = getattr(settings, setting_name("JSONFIELD_ENABLED"), False)
JSONFIELD_ENABLED = True if POSTGRES_JSONFIELD else getattr(settings, setting_name("JSONFIELD_ENABLED"), False)

if JSONFIELD_ENABLED:
JSONFIELD_CUSTOM = getattr(settings, setting_name("JSONFIELD_CUSTOM"), None)
Expand Down
10 changes: 7 additions & 3 deletions social_django/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@


class SocialAuthExceptionMiddleware:
"""Middleware that handles Social Auth AuthExceptions by providing the user
"""
Middleware that handles Social Auth AuthExceptions by providing the user
with a message, logging an error, and redirecting to some next location.

By default, the exception message itself is sent to the user and they are
Expand All @@ -30,7 +31,7 @@
def process_exception(self, request, exception):
strategy = getattr(request, "social_strategy", None)
if strategy is None or self.raise_exception(request, exception):
return
return None

if isinstance(exception, SocialAuthBaseException):
backend = getattr(request, "backend", None)
Expand All @@ -45,17 +46,20 @@
messages.error(request, message, extra_tags=f"social-auth {backend_name}")
except MessageFailure:
if url:
url += ("?" in url and "&" or "?") + f"message={quote(message)}&backend={backend_name}"
url += (("?" in url and "&") or "?") + f"message={quote(message)}&backend={backend_name}"
else:
social_logger.error(message)

if url:
return redirect(url)
return None
return None

def raise_exception(self, request, exception):
strategy = getattr(request, "social_strategy", None)
if strategy is not None:
return strategy.setting("RAISE_EXCEPTIONS", settings.DEBUG)
return None

Check warning on line 62 in social_django/middleware.py

View check run for this annotation

Codecov / codecov/patch

social_django/middleware.py#L62

Added line #L62 was not covered by tests

def get_message(self, request, exception):
return str(exception)
Expand Down
9 changes: 2 additions & 7 deletions social_django/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@
from django.db import migrations, models
from social_core.utils import setting_name

from ..fields import JSONField
from ..storage import (
DjangoAssociationMixin,
DjangoCodeMixin,
DjangoNonceMixin,
DjangoUserMixin,
)
from social_django.fields import JSONField
from social_django.storage import DjangoAssociationMixin, DjangoCodeMixin, DjangoNonceMixin, DjangoUserMixin

USER_MODEL = (
getattr(settings, setting_name("USER_MODEL"), None) or getattr(settings, "AUTH_USER_MODEL", None) or "auth.User"
Expand Down
4 changes: 2 additions & 2 deletions social_django/migrations/0004_auto_20160423_0400.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.db import migrations

from ..fields import JSONField
from social_django.fields import JSONField


class Migration(migrations.Migration):
Expand All @@ -18,5 +18,5 @@ class Migration(migrations.Migration):
model_name="usersocialauth",
name="extra_data",
field=JSONField(default=dict),
)
),
]
19 changes: 9 additions & 10 deletions social_django/migrations/0013_migrate_extra_data.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
# Generated by Django 4.0 on 2023-06-10 07:10

import contextlib
import json

from django.db import migrations, models

MAX_BATCH_SIZE = 1000


def migrate_json_field(apps, schema_editor):
UserSocialAuth = apps.get_model("social_django", "UserSocialAuth")
Expand All @@ -13,14 +16,12 @@
for auth in UserSocialAuth.objects.using(db_alias).exclude(extra_data='""').iterator():
old_value = auth.extra_data
if isinstance(old_value, str):
try:
with contextlib.suppress(json.JSONDecodeError):

Check warning on line 19 in social_django/migrations/0013_migrate_extra_data.py

View check run for this annotation

Codecov / codecov/patch

social_django/migrations/0013_migrate_extra_data.py#L19

Added line #L19 was not covered by tests
old_value = json.loads(old_value)
except json.JSONDecodeError as error:
print(f"Failed to migrate extra_data {old_value}: {error}")
auth.extra_data_new = old_value
to_be_updated.append(auth)

if len(to_be_updated) >= 1000:
if len(to_be_updated) >= MAX_BATCH_SIZE:
UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data_new"])
to_be_updated.clear()

Expand All @@ -31,10 +32,8 @@
for auth in Partial.objects.using(db_alias).all():
old_value = auth.data
if isinstance(old_value, str):
try:
with contextlib.suppress(json.JSONDecodeError):

Check warning on line 35 in social_django/migrations/0013_migrate_extra_data.py

View check run for this annotation

Codecov / codecov/patch

social_django/migrations/0013_migrate_extra_data.py#L35

Added line #L35 was not covered by tests
old_value = json.loads(old_value)
except json.JSONDecodeError as error:
print(f"Failed to migrate data {old_value}: {error}")
auth.data_new = old_value
auth.save(update_fields=["data_new"])

Expand All @@ -46,7 +45,7 @@
to_be_updated = []

is_text_field = isinstance(
UserSocialAuth._meta.get_field("extra_data"),
UserSocialAuth._meta.get_field("extra_data"), # noqa: SLF001
models.TextField,
)
for auth in UserSocialAuth.objects.using(db_alias).iterator():
Expand All @@ -56,7 +55,7 @@
auth.extra_data = new_value
to_be_updated.append(auth)

if len(to_be_updated) >= 1000:
if len(to_be_updated) >= MAX_BATCH_SIZE:
UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data"])
to_be_updated.clear()

Expand All @@ -65,7 +64,7 @@
to_be_updated.clear()

is_text_field = issubclass(
type(Partial._meta.get_field("data")),
type(Partial._meta.get_field("data")), # noqa: SLF001
models.TextField,
)
for auth in Partial.objects.using(db_alias).all():
Expand Down
8 changes: 4 additions & 4 deletions social_django/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ class AbstractUserSocialAuth(models.Model, DjangoUserMixin):
modified = models.DateTimeField(auto_now=True)
objects = UserSocialAuthManager()

def __str__(self):
return str(self.user)

class Meta:
constraints = [models.CheckConstraint(condition=~models.Q(uid=""), name="user_social_auth_uid_required")]
abstract = True

def __str__(self):
return str(self.user)

@classmethod
def get_social_auth(cls, provider: str, uid: str | int):
if not isinstance(uid, str):
Expand All @@ -57,7 +57,7 @@ def get_social_auth(cls, provider: str, uid: str | int):
@classmethod
def username_max_length(cls):
username_field = cls.username_field()
field = cls.user_model()._meta.get_field(username_field)
field = cls.user_model()._meta.get_field(username_field) # noqa: SLF001
return field.max_length

@classmethod
Expand Down
26 changes: 13 additions & 13 deletions social_django/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@ def allowed_to_disconnect(cls, user, backend_name, association_id=None):
qs = cls.objects.exclude(provider=backend_name)
qs = qs.filter(user=user)

if hasattr(user, "has_usable_password"):
valid_password = user.has_usable_password()
else:
valid_password = True
valid_password = user.has_usable_password() if hasattr(user, "has_usable_password") else True
return valid_password or qs.exists()

@classmethod
Expand All @@ -56,7 +53,7 @@ def user_exists(cls, *args, **kwargs):
"""
if "username" in kwargs:
kwargs[cls.username_field()] = kwargs.pop("username")
return cls.user_model()._default_manager.filter(*args, **kwargs).exists()
return cls.user_model()._default_manager.filter(*args, **kwargs).exists() # noqa: SLF001

@classmethod
def get_username(cls, user):
Expand All @@ -65,14 +62,15 @@ def get_username(cls, user):
@classmethod
def create_user(cls, *args, **kwargs):
username_field = cls.username_field()
manager = cls.user_model()._default_manager # noqa: SLF001
if "username" in kwargs:
if username_field not in kwargs:
kwargs[username_field] = kwargs.pop("username")
else:
# If username_field is 'email' and there is no field named "username"
# then latest should be removed from kwargs.
try:
cls.user_model()._meta.get_field("username")
cls.user_model()._meta.get_field("username") # noqa: SLF001
except FieldDoesNotExist:
kwargs.pop("username")
try:
Expand All @@ -83,33 +81,35 @@ def create_user(cls, *args, **kwargs):
# stays undamaged by wrapping the create in an atomic.
using = router.db_for_write(cls.user_model())
with transaction.atomic(using=using):
user = cls.user_model()._default_manager.create_user(*args, **kwargs)
user = manager.create_user(*args, **kwargs)
else:
user = cls.user_model()._default_manager.create_user(*args, **kwargs)
user = manager.create_user(*args, **kwargs)
except IntegrityError as exc:
# If email comes in as None it won't get found in the get
if kwargs.get("email", True) is None:
kwargs["email"] = ""
try:
user = cls.user_model()._default_manager.get(*args, **kwargs)
user = manager.get(*args, **kwargs)
except cls.user_model().DoesNotExist:
raise exc
raise exc from None
return user

@classmethod
def get_user(cls, pk=None, **kwargs):
if pk:
kwargs = {"pk": pk}
try:
return cls.user_model()._default_manager.get(**kwargs)
return cls.user_model()._default_manager.get(**kwargs) # noqa: SLF001
except cls.user_model().DoesNotExist:
return None

@classmethod
def get_users_by_email(cls, email):
user_model = cls.user_model()
email_field = getattr(user_model, "EMAIL_FIELD", "email")
return user_model._default_manager.filter(**{email_field + "__iexact": email})
return user_model._default_manager.filter( # noqa: SLF001
**{email_field + "__iexact": email}
)

@classmethod
def get_social_auth(cls, provider, uid):
Expand All @@ -121,7 +121,7 @@ def get_social_auth(cls, provider, uid):
return None

@classmethod
def get_social_auth_for_user(cls, user, provider=None, id=None):
def get_social_auth_for_user(cls, user, provider=None, id=None): # noqa: A002
qs = cls.objects.filter(user=user)

if provider:
Expand Down
Loading