Can I use get_or_create() in django to assign a global variable?
I am an intern at a company and we are using django as framework.
I was working on a two part register system in which an admin performs the initial registration after which a link is sent to the user via, SMS so the user could complete the registration.
I have a feeling to use the get_or_create function to assign a global variable but I'm afraid to break this (I use git but I am still scared).
class RegisterSerializer(serializers.ModelSerializer):
"""Class for registering users with multiple groups."""
# is_superuser = serializers.BooleanField(default=False, required=False, write_only=True)
class Meta:
fields = [
"national_code",
"phone_number",
]
model = User
extra_kwargs = {
"national_code": {"write_only": True, "validators": []},
"phone_number": {"write_only": True, "validators": []},
}
def validate(self, attrs):
if not attrs.get("national_code"):
raise serializers.ValidationError(_("National code is required."))
if not attrs.get("phone_number"):
raise serializers.ValidationError(_("Phone number is required."))
if User.objects.filter(
phone_number=attrs.get("phone_number"),
national_code=attrs.get("national_code"),
is_complete=True,
).exists():
raise serializers.ValidationError(_("user already exists"))
# if User.objects.filter(phone_number=attrs.get("phone_number")).exists():
# raise serializers.ValidationError(_("Phone number already exist."))
return attrs
def create(self, validated_data):
phone_number = validated_data["phone_number"]
national_code = validated_data["national_code"]
user, created = User.objects.get_or_create(
phone_number=phone_number, national_code=national_code, defaults={"is_complete": False}
)
token = RegisterToken.for_user(user)
try:
Sms.sendSMS(
phone_number,
f"{str(settings.DOMAIN_NAME)}/api/accounts/complete-register/?token={str(token)}",
)
# do not delete this part soon or later we will use this
# Sms.SendRegisterLink(
# phone_number,
# [
# {
# 'national_code':national_code,
# 'domain_name':settings.DOMAIN_NAME,
# 'token':token
# },
# ],
# )
return user
except Exception as err:
raise ValidationError(_("Failed to send SMS: ") + str(err)) from err
I have a feeling to use the get_or_create function to assign a global variable but I'm afraid to break this.
Please don't. Global variables are a (very) bad idea from a software design point of view, but even more when you create a webserver.
Usually multiple workers are used in a production environment: for example Gunicorn can spin up ~6 workers that will each do a bit of work. As a result the first request might end at a different worker than the second one, and therefore it might not work.
Usually if you need global state, you use a database to maintain the state, or for example a redis memory cache, such that multiple workers all have access to the same global state.