Skip to content

Commit 40b5855

Browse files
committed
Ran black 🎨
1 parent f2c7f44 commit 40b5855

File tree

12 files changed

+52
-149
lines changed

12 files changed

+52
-149
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ repos:
44
rev: 22.10.0
55
hooks:
66
- id: black
7-
7+
args:
8+
- --line-length=100
89
- repo: https://github.com/PyCQA/flake8
910
rev: 5.0.4
1011
hooks:

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ docs:
6464
python setup.py build_sphinx
6565

6666
lint:
67-
flake8 --exclude=*/migrations/* --max-line-length 88 drf_user
67+
flake8 --exclude=*/migrations/* --max-line-length 100 drf_user
6868

6969
format:
7070
black --exclude .+/migrations/.+\.py drf_user

drf_user/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,7 @@ def update_user_settings() -> dict:
6060
user_settings["OTP"][otp_key] = otp_value
6161
elif key == "REGISTRATION":
6262
if not isinstance(value, dict):
63-
raise TypeError(
64-
"USER_SETTING attribute REGISTRATION must be a dict."
65-
)
63+
raise TypeError("USER_SETTING attribute REGISTRATION must be a dict.")
6664
for reg_key, reg_value in value.items():
6765
user_settings["REGISTRATION"][reg_key] = reg_value
6866
if user_settings["REGISTRATION"]["SEND_MAIL"]:

drf_user/managers.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,7 @@ def _create_user(
3030
Creates and saves a User with given details
3131
"""
3232
email = self.normalize_email(email)
33-
user = self.model(
34-
username=username, email=email, name=fullname, mobile=mobile, **kwargs
35-
)
33+
user = self.model(username=username, email=email, name=fullname, mobile=mobile, **kwargs)
3634
user.set_password(password)
3735
user.save(using=self._db)
3836
return user

drf_user/models.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@ class User(AbstractBaseUser, PermissionsMixin):
3333
Author: Himanshu Shankar (https://himanshus.com)
3434
"""
3535

36-
username = models.CharField(
37-
verbose_name=_("Unique UserName"), max_length=254, unique=True
38-
)
36+
username = models.CharField(verbose_name=_("Unique UserName"), max_length=254, unique=True)
3937
email = models.EmailField(verbose_name=_("Email Address"), unique=True)
4038
mobile = models.CharField(
4139
verbose_name=_("Mobile Number"),
@@ -103,15 +101,9 @@ class AuthTransaction(models.Model):
103101
blank=True,
104102
verbose_name=_("JWT Refresh Token"),
105103
)
106-
expires_at = models.DateTimeField(
107-
blank=True, null=True, verbose_name=_("Expires At")
108-
)
109-
create_date = models.DateTimeField(
110-
verbose_name=_("Create Date/Time"), auto_now_add=True
111-
)
112-
update_date = models.DateTimeField(
113-
verbose_name=_("Date/Time Modified"), auto_now=True
114-
)
104+
expires_at = models.DateTimeField(blank=True, null=True, verbose_name=_("Expires At"))
105+
create_date = models.DateTimeField(verbose_name=_("Create Date/Time"), auto_now_add=True)
106+
update_date = models.DateTimeField(verbose_name=_("Date/Time Modified"), auto_now=True)
115107
created_by = models.ForeignKey(to=User, on_delete=models.PROTECT)
116108

117109
def __str__(self):
@@ -142,19 +134,15 @@ class OTPValidation(models.Model):
142134
create_date = models.DateTimeField(verbose_name=_("Create Date"), auto_now_add=True)
143135
update_date = models.DateTimeField(verbose_name=_("Date Modified"), auto_now=True)
144136
is_validated = models.BooleanField(verbose_name=_("Is Validated"), default=False)
145-
validate_attempt = models.IntegerField(
146-
verbose_name=_("Attempted Validation"), default=3
147-
)
137+
validate_attempt = models.IntegerField(verbose_name=_("Attempted Validation"), default=3)
148138
prop = models.CharField(
149139
verbose_name=_("Destination Property"),
150140
default=EMAIL,
151141
max_length=3,
152142
choices=DESTINATION_CHOICES,
153143
)
154144
send_counter = models.IntegerField(verbose_name=_("OTP Sent Counter"), default=0)
155-
sms_id = models.CharField(
156-
verbose_name=_("SMS ID"), max_length=254, null=True, blank=True
157-
)
145+
sms_id = models.CharField(verbose_name=_("SMS ID"), max_length=254, null=True, blank=True)
158146
reactive_at = models.DateTimeField(verbose_name=_("ReActivate Sending OTP"))
159147

160148
def __str__(self):

drf_user/serializers.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,7 @@ def validate_email(self, value: str) -> str:
3838
if check_validation(value=value):
3939
return value
4040
else:
41-
raise serializers.ValidationError(
42-
"The email must be " "pre-validated via OTP."
43-
)
41+
raise serializers.ValidationError("The email must be " "pre-validated via OTP.")
4442

4543
def validate_mobile(self, value: str) -> str:
4644
"""
@@ -61,9 +59,7 @@ def validate_mobile(self, value: str) -> str:
6159
if check_validation(value=value):
6260
return value
6361
else:
64-
raise serializers.ValidationError(
65-
"The mobile must be " "pre-validated via OTP."
66-
)
62+
raise serializers.ValidationError("The mobile must be " "pre-validated via OTP.")
6763

6864
def validate_password(self, value: str) -> str:
6965
"""Validate whether the password meets all django validator requirements."""
@@ -201,9 +197,7 @@ def validate(self, attrs: dict) -> dict:
201197
raise NotFound(_("No user exists with provided details"))
202198
if "email" not in attrs.keys() and "verify_otp" not in attrs.keys():
203199
raise serializers.ValidationError(
204-
_(
205-
"Email field is compulsory while verifying a non-existing user's OTP."
206-
)
200+
_("Email field is compulsory while verifying a non-existing user's OTP.")
207201
)
208202
else:
209203
attrs["email"] = user.email
@@ -274,9 +268,7 @@ def get_user(email: str, mobile: str):
274268
def validate(self, attrs: dict) -> dict:
275269
"""Validates the response"""
276270

277-
attrs["user"] = self.get_user(
278-
email=attrs.get("email"), mobile=attrs.get("mobile")
279-
)
271+
attrs["user"] = self.get_user(email=attrs.get("email"), mobile=attrs.get("mobile"))
280272
return attrs
281273

282274

@@ -362,9 +354,7 @@ class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
362354
certain extra data in payload such as: email, mobile, name
363355
"""
364356

365-
default_error_messages = {
366-
"no_active_account": _("username or password is invalid.")
367-
}
357+
default_error_messages = {"no_active_account": _("username or password is invalid.")}
368358

369359
@classmethod
370360
def get_token(cls, user):

drf_user/urls.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,9 @@
2323
name="Retrieve Update Profile",
2424
),
2525
# ex: api/user/password/reset/
26-
path(
27-
"password/reset/", views.PasswordResetView.as_view(), name="reset_user_password"
28-
),
26+
path("password/reset/", views.PasswordResetView.as_view(), name="reset_user_password"),
2927
# ex: api/user/upload-image/
3028
path("upload-image/", views.UploadImageView.as_view(), name="upload_profile_image"),
3129
# ex: api/user/refresh-token/
32-
path(
33-
"refresh-token/", views.CustomTokenRefreshView.as_view(), name="refresh_token"
34-
),
30+
path("refresh-token/", views.CustomTokenRefreshView.as_view(), name="refresh_token"),
3531
]

drf_user/utils.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,7 @@ def generate_otp(*, destination_property: str, destination: str) -> OTPValidatio
130130

131131
# Checks if random number is unique among non-validated OTPs and
132132
# creates new until it is unique.
133-
while OTPValidation.objects.filter(otp__exact=random_number).filter(
134-
is_validated=False
135-
):
133+
while OTPValidation.objects.filter(otp__exact=random_number).filter(is_validated=False):
136134
random_number: str = User.objects.make_random_password(
137135
length=otp_settings["LENGTH"], allowed_chars=otp_settings["ALLOWED_CHARS"]
138136
)
@@ -299,17 +297,13 @@ def validate_otp(*, destination: str, otp_val: int) -> bool:
299297
elif otp_object.validate_attempt <= 0:
300298
# check if attempts exceeded and regenerate otp and raise error
301299
generate_otp(destination_property=otp_object.prop, destination=destination)
302-
raise AuthenticationFailed(
303-
detail=_("Incorrect OTP. Attempt exceeded! OTP has been reset.")
304-
)
300+
raise AuthenticationFailed(detail=_("Incorrect OTP. Attempt exceeded! OTP has been reset."))
305301

306302
else:
307303
# update attempts and raise error
308304
otp_object.save(update_fields=["validate_attempt"])
309305
raise AuthenticationFailed(
310-
detail=_(
311-
f"OTP Validation failed! {otp_object.validate_attempt} attempts left!"
312-
)
306+
detail=_(f"OTP Validation failed! {otp_object.validate_attempt} attempts left!")
313307
)
314308

315309

@@ -343,9 +337,7 @@ def send_message(
343337
sent = {"success": False, "message": None, "mobile_message": None}
344338

345339
if not getattr(settings, "EMAIL_HOST", None):
346-
raise ValueError(
347-
"EMAIL_HOST must be defined in django setting for sending mail."
348-
)
340+
raise ValueError("EMAIL_HOST must be defined in django setting for sending mail.")
349341
if not getattr(settings, "EMAIL_FROM", None):
350342
raise ValueError(
351343
"EMAIL_FROM must be defined in django setting "
@@ -416,13 +408,9 @@ def send_otp(
416408
)
417409

418410
try:
419-
data: dict = send_message(
420-
message, otp_settings["SUBJECT"], recip_email, recip_mobile
421-
)
411+
data: dict = send_message(message, otp_settings["SUBJECT"], recip_email, recip_mobile)
422412
except (ValueError, ValidationError) as e:
423-
raise serializers.ValidationError(
424-
{"detail": f"OTP sending failed! because {e}"}
425-
) from e
413+
raise serializers.ValidationError({"detail": f"OTP sending failed! because {e}"}) from e
426414

427415
otp_obj.reactive_at = timezone.now() + datetime.timedelta(
428416
minutes=otp_settings["COOLING_PERIOD"]

drf_user/views.py

Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -193,21 +193,15 @@ def post(self, request, *args, **kwargs):
193193
destination: str = serializer.validated_data[
194194
"destination"
195195
] # destination is a required field
196-
destination_property: str = serializer.validated_data.get(
197-
"prop"
198-
) # can be email or mobile
196+
destination_property: str = serializer.validated_data.get("prop") # can be email or mobile
199197
user: User = serializer.validated_data.get("user")
200198
email: Optional[str] = serializer.validated_data.get("email")
201199
is_login: bool = serializer.validated_data.get("is_login")
202200

203201
if "verify_otp" in request.data.keys():
204-
if validate_otp(
205-
destination=destination, otp_val=request.data["verify_otp"]
206-
):
202+
if validate_otp(destination=destination, otp_val=request.data["verify_otp"]):
207203
if is_login:
208-
return Response(
209-
login_user(user, self.request), status=status.HTTP_202_ACCEPTED
210-
)
204+
return Response(login_user(user, self.request), status=status.HTTP_202_ACCEPTED)
211205
else:
212206
return Response(
213207
data={"OTP": _("OTP Validated successfully!")},
@@ -257,9 +251,7 @@ def get_object(self):
257251
def update(self, request, *args, **kwargs):
258252
"""Updates user's password"""
259253

260-
response = super(RetrieveUpdateUserAccountView, self).update(
261-
request, *args, **kwargs
262-
)
254+
response = super(RetrieveUpdateUserAccountView, self).update(request, *args, **kwargs)
263255
# we need to set_password after save the user otherwise it'll save the raw_password in db. # noqa
264256
if "password" in request.data.keys():
265257
self.request.user.set_password(request.data["password"])
@@ -311,17 +303,11 @@ def post(self, request, *args, **kwargs):
311303
)
312304
user.is_active = True
313305
user.save(update_fields=["is_active"])
314-
return Response(
315-
login_user(user, self.request), status=status.HTTP_202_ACCEPTED
316-
)
306+
return Response(login_user(user, self.request), status=status.HTTP_202_ACCEPTED)
317307

318-
otp_obj: OTPValidation = generate_otp(
319-
destination_property=EMAIL, destination=email
320-
)
308+
otp_obj: OTPValidation = generate_otp(destination_property=EMAIL, destination=email)
321309
# Send OTP to Email & Mobile
322-
sent_otp_resp: dict = send_otp(
323-
otp_obj=otp_obj, recip_email=email, recip_mobile=mobile
324-
)
310+
sent_otp_resp: dict = send_otp(otp_obj=otp_obj, recip_email=email, recip_mobile=mobile)
325311

326312
if not sent_otp_resp["success"]:
327313
raise serializers.ValidationError(
@@ -394,9 +380,7 @@ def post(self, request, *args, **kwargs):
394380
image_serializer.update(
395381
instance=request.user, validated_data=image_serializer.validated_data
396382
)
397-
return Response(
398-
{"detail": "Profile Image Uploaded."}, status=status.HTTP_201_CREATED
399-
)
383+
return Response({"detail": "Profile Image Uploaded."}, status=status.HTTP_201_CREATED)
400384

401385

402386
class CustomTokenRefreshView(TokenRefreshView):
@@ -419,13 +403,9 @@ def post(self, request, *args, **kwargs):
419403

420404
token = serializer.validated_data.get("access")
421405

422-
auth_transaction = AuthTransaction.objects.get(
423-
refresh_token=request.data["refresh"]
424-
)
406+
auth_transaction = AuthTransaction.objects.get(refresh_token=request.data["refresh"])
425407
auth_transaction.token = token
426-
auth_transaction.expires_at = (
427-
timezone.now() + api_settings.ACCESS_TOKEN_LIFETIME
428-
)
408+
auth_transaction.expires_at = timezone.now() + api_settings.ACCESS_TOKEN_LIFETIME
429409
auth_transaction.save(update_fields=["token", "expires_at"])
430410

431411
return Response({"token": str(token)}, status=status.HTTP_200_OK)

example/demo_app/urls.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,5 @@
4848
schema_view.with_ui("swagger", cache_timeout=0),
4949
name="schema-swagger-ui",
5050
),
51-
re_path(
52-
r"^redoc/$", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"
53-
),
51+
re_path(r"^redoc/$", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),
5452
]

0 commit comments

Comments
 (0)