Django操作数据库实现注册&登录验证

前几天就做完了这个登录&注册的后台(我觉得做后台比做前端省事多了),一直没空写……今天抽空给他写出来做下记录。

Model 定义

没啥说的,直接放代码

from django.db import models

class UserInfo(models.Model):
    user_id = models.IntegerField(primary_key=True)
    user_name = models.CharField(max_length=30)
    pass_word = models.CharField(max_length=64)
    user_token = models.CharField(max_length=64)
    token_last_modified = models.DateTimeField()

    def __unicode__(self):
        return self.user_name

前端发来的数据处理

图省事,前端直接发Json过来。不多说,直接扔代码~

#登录
@ensure_csrf_cookie
def login_authentication(request):
    if request.method != "POST":
        return HttpResponse()
    login_state = {}
    try:
        user_info = json.loads(bytes.decode(request.body))
        db_info = UserInfo.objects.get(user_name=user_info["userName"])
        if db_info.pass_word == user_info["userPassWD"]:
            login_state['authState'] = AuthEnum.LoginSuccess
            login_state['userID'] = db_info.user_id
            login_state['userToken'] = db_info.user_token
        else:
            raise ObjectDoesNotExist()
    except ObjectDoesNotExist:
        login_state['authState'] = AuthEnum.PasswordNotMatch
    except KeyError:
        login_state['authState'] = AuthEnum.BrokenJson
    finally:
        http_response = HttpResponse(json.dumps(login_state))
    return http_response

django收到的request,body是的格式为bytes。所以需要先decode,然后才能json.load()转成json。
对于json的访问跟字典很像,Key-Value。
其次就是Django获取数据库的内容了。
UserInfo.objects.get,一个函数,就可以获得这个对象了。如果没有找到,会抛出ObjectDoesNotExist异常。
对于得到的对象的其他值的访问,通过 obj.name即可访问。

最后就是字典转json这个,使用json.dumps即可~

注册功能的实现

# 直接网上找的随机字符串生成代码= =
def get_random_str(random_str_length=64):
    strings = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(random_str_length):
        strings += chars[random.randint(0, length)]
    return strings
# 数据验证
def valid_register_info(info):
    if info["userName"] == "" or len(info["userPassWD"]) != 64:
        print(info["userName"])
        print(len(info["userPassWD"]))
        raise KeyError
# 注册
@ensure_csrf_cookie
def register_user(request):
    if request.method != "POST":
        return HttpResponse()
    register_state = {}
    user_info = json.loads(bytes.decode(request.body))
    try:
        valid_register_info(user_info)
        UserInfo.objects.get(user_name=user_info["userName"])
        register_state['authState'] = RegisterEnum.UserNameDuplication
    except ObjectDoesNotExist:
        if UserInfo.objects.last() is None:
            user_id = 1
        else:
            user_id = UserInfo.objects.last().user_id + 1
        UserInfo.objects.create(user_name=user_info["userName"], user_id=user_id,
                                pass_word=user_info["userPassWD"], user_token=get_random_str(64),
                                token_last_modified=timezone.now())
        register_state['authState'] = RegisterEnum.RegisterSuccess
    except KeyError:
        register_state['authState'] = RegisterEnum.BrokenJson
    finally:
        http_response = HttpResponse(json.dumps(register_state))
    return http_response

挑重点的说吧
UserInfo.objects.create,往数据库添加数据,后面跟着值。
UserInfo.objects.last(),获取数据库中最后一条记录,若数据库为空,则返回None。
我觉得没什么说的了……

附加

python3 manage.py makemigrations
yisilepython3 manage.py migrate

相信各位知道我什么意思了……

你可能感兴趣的:(Python)