Skip to content

Commit 7a7f172

Browse files
committed
chore: apply more ruff fixes
1 parent b3299c0 commit 7a7f172

22 files changed

+144
-111
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ repos:
1919
- repo: https://github.com/astral-sh/ruff-pre-commit
2020
rev: v0.11.11
2121
hooks:
22-
- id: ruff
22+
- id: ruff-check
2323
args: [--fix, --exit-non-zero-on-fix]
2424
- id: ruff-format
2525
- repo: meta

manage.py

100644100755
File mode changed.

pyproject.toml

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,32 @@ exclude = [
104104
"site"
105105
]
106106
line-length = 120
107-
output-format = "github"
108107

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

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

129+
[tool.ruff.lint.per-file-ignores]
130+
"social_django/migrations/*.py" = ["RUF012"]
131+
"tests/settings.py" = ["PTH"]
132+
116133
[tool.setuptools]
117134
packages = ["social_django"]
118135

social_django/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,4 @@ def fake_init(self, strategy=None, *args, **kwargs):
2323

2424
if not getattr(BaseAuth, "__init_patched", False):
2525
BaseAuth.__init__ = baseauth_init_workaround(BaseAuth.__init__) # type: ignore[method-assign]
26-
BaseAuth.__init_patched = True # type: ignore[attr-defined]
26+
BaseAuth.__init_patched = True # type: ignore[attr-defined] # noqa: SLF001

social_django/admin.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@ class UserSocialAuthOption(admin.ModelAdmin):
2222
def get_search_fields(self, request=None):
2323
search_fields = getattr(settings, setting_name("ADMIN_USER_SEARCH_FIELDS"), None)
2424
if search_fields is None:
25-
_User = UserSocialAuth.user_model()
26-
username = getattr(_User, "USERNAME_FIELD", None) or hasattr(_User, "username") and "username" or None
25+
_User = UserSocialAuth.user_model() # noqa: N806
26+
username = getattr(_User, "USERNAME_FIELD", None) or (hasattr(_User, "username") and "username") or None
2727
fieldnames = ("first_name", "last_name", "email", username)
28-
all_names = self._get_all_field_names(_User._meta)
28+
all_names = self._get_all_field_names(
29+
_User._meta # noqa: SLF001
30+
)
2931
search_fields = [name for name in fieldnames if name and name in all_names]
3032
return ["user__" + name for name in search_fields] + getattr(settings, setting_name("ADMIN_SEARCH_FIELDS"), [])
3133

social_django/context_processors.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,18 @@ def __setitem__(self, name, value):
2424

2525

2626
def backends(request):
27-
"""Load Social Auth current user data to context under the key 'backends'.
28-
Will return the output of social_core.backends.utils.user_backends_data."""
27+
"""
28+
Load Social Auth current user data to context under the key 'backends'.
29+
Will return the output of social_core.backends.utils.user_backends_data.
30+
"""
2931
return {"backends": LazyDict(lambda: user_backends_data(request.user, settings.AUTHENTICATION_BACKENDS, Storage))}
3032

3133

3234
def login_redirect(request):
3335
"""Load current redirect to context."""
3436
try:
35-
value = (
36-
request.method == "POST" and request.POST.get(REDIRECT_FIELD_NAME) or request.GET.get(REDIRECT_FIELD_NAME)
37+
value = (request.method == "POST" and request.POST.get(REDIRECT_FIELD_NAME)) or request.GET.get(
38+
REDIRECT_FIELD_NAME
3739
)
3840
except MultiPartParserError:
3941
# request POST may be malformed

social_django/fields.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@
88

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

11-
if POSTGRES_JSONFIELD:
12-
JSONFIELD_ENABLED = True
13-
else:
14-
JSONFIELD_ENABLED = getattr(settings, setting_name("JSONFIELD_ENABLED"), False)
11+
JSONFIELD_ENABLED = True if POSTGRES_JSONFIELD else getattr(settings, setting_name("JSONFIELD_ENABLED"), False)
1512

1613
if JSONFIELD_ENABLED:
1714
JSONFIELD_CUSTOM = getattr(settings, setting_name("JSONFIELD_CUSTOM"), None)

social_django/middleware.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010

1111

1212
class SocialAuthExceptionMiddleware:
13-
"""Middleware that handles Social Auth AuthExceptions by providing the user
13+
"""
14+
Middleware that handles Social Auth AuthExceptions by providing the user
1415
with a message, logging an error, and redirecting to some next location.
1516
1617
By default, the exception message itself is sent to the user and they are
@@ -30,7 +31,7 @@ def __call__(self, request):
3031
def process_exception(self, request, exception):
3132
strategy = getattr(request, "social_strategy", None)
3233
if strategy is None or self.raise_exception(request, exception):
33-
return
34+
return None
3435

3536
if isinstance(exception, SocialAuthBaseException):
3637
backend = getattr(request, "backend", None)
@@ -45,17 +46,20 @@ def process_exception(self, request, exception):
4546
messages.error(request, message, extra_tags=f"social-auth {backend_name}")
4647
except MessageFailure:
4748
if url:
48-
url += ("?" in url and "&" or "?") + f"message={quote(message)}&backend={backend_name}"
49+
url += (("?" in url and "&") or "?") + f"message={quote(message)}&backend={backend_name}"
4950
else:
5051
social_logger.error(message)
5152

5253
if url:
5354
return redirect(url)
55+
return None
56+
return None
5457

5558
def raise_exception(self, request, exception):
5659
strategy = getattr(request, "social_strategy", None)
5760
if strategy is not None:
5861
return strategy.setting("RAISE_EXCEPTIONS", settings.DEBUG)
62+
return None
5963

6064
def get_message(self, request, exception):
6165
return str(exception)

social_django/migrations/0001_initial.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,8 @@
22
from django.db import migrations, models
33
from social_core.utils import setting_name
44

5-
from ..fields import JSONField
6-
from ..storage import (
7-
DjangoAssociationMixin,
8-
DjangoCodeMixin,
9-
DjangoNonceMixin,
10-
DjangoUserMixin,
11-
)
5+
from social_django.fields import JSONField
6+
from social_django.storage import DjangoAssociationMixin, DjangoCodeMixin, DjangoNonceMixin, DjangoUserMixin
127

138
USER_MODEL = (
149
getattr(settings, setting_name("USER_MODEL"), None) or getattr(settings, "AUTH_USER_MODEL", None) or "auth.User"

social_django/migrations/0004_auto_20160423_0400.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from django.db import migrations
22

3-
from ..fields import JSONField
3+
from social_django.fields import JSONField
44

55

66
class Migration(migrations.Migration):
@@ -18,5 +18,5 @@ class Migration(migrations.Migration):
1818
model_name="usersocialauth",
1919
name="extra_data",
2020
field=JSONField(default=dict),
21-
)
21+
),
2222
]

social_django/migrations/0013_migrate_extra_data.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
# Generated by Django 4.0 on 2023-06-10 07:10
22

3+
import contextlib
34
import json
45

56
from django.db import migrations, models
67

8+
MAX_BATCH_SIZE = 1000
9+
710

811
def migrate_json_field(apps, schema_editor):
912
UserSocialAuth = apps.get_model("social_django", "UserSocialAuth")
@@ -13,14 +16,12 @@ def migrate_json_field(apps, schema_editor):
1316
for auth in UserSocialAuth.objects.using(db_alias).exclude(extra_data='""').iterator():
1417
old_value = auth.extra_data
1518
if isinstance(old_value, str):
16-
try:
19+
with contextlib.suppress(json.JSONDecodeError):
1720
old_value = json.loads(old_value)
18-
except json.JSONDecodeError as error:
19-
print(f"Failed to migrate extra_data {old_value}: {error}")
2021
auth.extra_data_new = old_value
2122
to_be_updated.append(auth)
2223

23-
if len(to_be_updated) >= 1000:
24+
if len(to_be_updated) >= MAX_BATCH_SIZE:
2425
UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data_new"])
2526
to_be_updated.clear()
2627

@@ -31,10 +32,8 @@ def migrate_json_field(apps, schema_editor):
3132
for auth in Partial.objects.using(db_alias).all():
3233
old_value = auth.data
3334
if isinstance(old_value, str):
34-
try:
35+
with contextlib.suppress(json.JSONDecodeError):
3536
old_value = json.loads(old_value)
36-
except json.JSONDecodeError as error:
37-
print(f"Failed to migrate data {old_value}: {error}")
3837
auth.data_new = old_value
3938
auth.save(update_fields=["data_new"])
4039

@@ -46,7 +45,7 @@ def migrate_json_field_backwards(apps, schema_editor):
4645
to_be_updated = []
4746

4847
is_text_field = isinstance(
49-
UserSocialAuth._meta.get_field("extra_data"),
48+
UserSocialAuth._meta.get_field("extra_data"), # noqa: SLF001
5049
models.TextField,
5150
)
5251
for auth in UserSocialAuth.objects.using(db_alias).iterator():
@@ -56,7 +55,7 @@ def migrate_json_field_backwards(apps, schema_editor):
5655
auth.extra_data = new_value
5756
to_be_updated.append(auth)
5857

59-
if len(to_be_updated) >= 1000:
58+
if len(to_be_updated) >= MAX_BATCH_SIZE:
6059
UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data"])
6160
to_be_updated.clear()
6261

@@ -65,7 +64,7 @@ def migrate_json_field_backwards(apps, schema_editor):
6564
to_be_updated.clear()
6665

6766
is_text_field = issubclass(
68-
type(Partial._meta.get_field("data")),
67+
type(Partial._meta.get_field("data")), # noqa: SLF001
6968
models.TextField,
7069
)
7170
for auth in Partial.objects.using(db_alias).all():

social_django/models.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,13 @@ class AbstractUserSocialAuth(models.Model, DjangoUserMixin):
3636
modified = models.DateTimeField(auto_now=True)
3737
objects = UserSocialAuthManager()
3838

39-
def __str__(self):
40-
return str(self.user)
41-
4239
class Meta:
4340
constraints = [models.CheckConstraint(condition=~models.Q(uid=""), name="user_social_auth_uid_required")]
4441
abstract = True
4542

43+
def __str__(self):
44+
return str(self.user)
45+
4646
@classmethod
4747
def get_social_auth(cls, provider: str, uid: str | int):
4848
if not isinstance(uid, str):
@@ -57,7 +57,7 @@ def get_social_auth(cls, provider: str, uid: str | int):
5757
@classmethod
5858
def username_max_length(cls):
5959
username_field = cls.username_field()
60-
field = cls.user_model()._meta.get_field(username_field)
60+
field = cls.user_model()._meta.get_field(username_field) # noqa: SLF001
6161
return field.max_length
6262

6363
@classmethod

social_django/storage.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,7 @@ def allowed_to_disconnect(cls, user, backend_name, association_id=None):
3434
qs = cls.objects.exclude(provider=backend_name)
3535
qs = qs.filter(user=user)
3636

37-
if hasattr(user, "has_usable_password"):
38-
valid_password = user.has_usable_password()
39-
else:
40-
valid_password = True
37+
valid_password = user.has_usable_password() if hasattr(user, "has_usable_password") else True
4138
return valid_password or qs.exists()
4239

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

6158
@classmethod
6259
def get_username(cls, user):
@@ -65,14 +62,15 @@ def get_username(cls, user):
6562
@classmethod
6663
def create_user(cls, *args, **kwargs):
6764
username_field = cls.username_field()
65+
manager = cls.user_model()._default_manager # noqa: SLF001
6866
if "username" in kwargs:
6967
if username_field not in kwargs:
7068
kwargs[username_field] = kwargs.pop("username")
7169
else:
7270
# If username_field is 'email' and there is no field named "username"
7371
# then latest should be removed from kwargs.
7472
try:
75-
cls.user_model()._meta.get_field("username")
73+
cls.user_model()._meta.get_field("username") # noqa: SLF001
7674
except FieldDoesNotExist:
7775
kwargs.pop("username")
7876
try:
@@ -83,33 +81,35 @@ def create_user(cls, *args, **kwargs):
8381
# stays undamaged by wrapping the create in an atomic.
8482
using = router.db_for_write(cls.user_model())
8583
with transaction.atomic(using=using):
86-
user = cls.user_model()._default_manager.create_user(*args, **kwargs)
84+
user = manager.create_user(*args, **kwargs)
8785
else:
88-
user = cls.user_model()._default_manager.create_user(*args, **kwargs)
86+
user = manager.create_user(*args, **kwargs)
8987
except IntegrityError as exc:
9088
# If email comes in as None it won't get found in the get
9189
if kwargs.get("email", True) is None:
9290
kwargs["email"] = ""
9391
try:
94-
user = cls.user_model()._default_manager.get(*args, **kwargs)
92+
user = manager.get(*args, **kwargs)
9593
except cls.user_model().DoesNotExist:
96-
raise exc
94+
raise exc from None
9795
return user
9896

9997
@classmethod
10098
def get_user(cls, pk=None, **kwargs):
10199
if pk:
102100
kwargs = {"pk": pk}
103101
try:
104-
return cls.user_model()._default_manager.get(**kwargs)
102+
return cls.user_model()._default_manager.get(**kwargs) # noqa: SLF001
105103
except cls.user_model().DoesNotExist:
106104
return None
107105

108106
@classmethod
109107
def get_users_by_email(cls, email):
110108
user_model = cls.user_model()
111109
email_field = getattr(user_model, "EMAIL_FIELD", "email")
112-
return user_model._default_manager.filter(**{email_field + "__iexact": email})
110+
return user_model._default_manager.filter( # noqa: SLF001
111+
**{email_field + "__iexact": email}
112+
)
113113

114114
@classmethod
115115
def get_social_auth(cls, provider, uid):
@@ -121,7 +121,7 @@ def get_social_auth(cls, provider, uid):
121121
return None
122122

123123
@classmethod
124-
def get_social_auth_for_user(cls, user, provider=None, id=None):
124+
def get_social_auth_for_user(cls, user, provider=None, id=None): # noqa: A002
125125
qs = cls.objects.filter(user=user)
126126

127127
if provider:

0 commit comments

Comments
 (0)