今天我们要分享的是,撰写一支简易注册功能的API,先来到我们的views档案,如同我们之前所说Views档案就是传递讯息桥梁以及撰写主要逻辑的地方,底下是我的程序码
from datetime import datetime
import json
import uuid
from django.contrib.auth.models import User
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_protect
from user.models import UserProfile
@csrf_protect
def register(request):
if request.method == "POST":
try:
data = json.loads(bytes.decode(request.body,"utf-8"))
account = data["account"]
password = data["password"]
email = data["email"]
phone = data["phone"]
id = uuid.uuid5(uuid.NAMESPACE_DNS,account)
check_account = UserProfile.objects.filter(account=account).first()
if check_account is None :
user = UserProfile.objects.create_user(id=id,username=account,account=account,email=email,phone=phone)
user.set_password(password)
user.save()
message = {"status" : "注册成功"}
else :
message = {"status" : "注册失败,帐号已注册"}
except Exception as e:
message = {"status" : "error"}
return JsonResponse(message)
这里简单说明一下我的想法,我的想法是利用uuid5产生一个唯一值能够作为pk,使用filter().first()查询是否已经有使用相同帐号注册的使用者,如果有返回并非None,以此判断重复注册,如果判断没有重复注册则创建一个使用者资料。
接着说明一下function
@csrf_protect
:来预防csrf攻击,如果不用的话可以改用@csrf_exempt
。
if request.method == "POST":
:判断HTTP method是否为POST。
data = json.loads(bytes.decode(request.body,"utf-8"))
:把原始request的资料层层解码转换格式。
account = data["account"]
:读取account key里的value。
id = uuid.uuid5(uuid.NAMESPACE_DNS,account)
:使用uuid5的方式对account做加密处理产生一组uuid。
check_account = UserProfile.objects.filter(account=account).first()
:从资料库中抓取第一笔符合account=account的资料(例如资料库已经有account=abc123),就会返回,若没有就返回None,以这个为依据判断是否重复注册。
user=UserProfile.objects.create_user(id=id,username=account,account=account,email=email,phone=phone)
:使用UserProfile的资料格式,建立()中输入的资料
这里有官方文件,里面有对於csrf_protect更详细的介绍唷。
今天就先到这边啦~~ 预告一下我们明天即将要进入urls。
阿对了,今天有提到csrf,如果有夥伴对这些有疑问,在urls过後,要测试API之前我会再跟各位夥伴补充说明,请夥伴们见谅ˊ V ˋ
<<: Day25:安全性和演算法-讯息监别码(Message Authentication Code)
笔者昨日与三五好友相约在猫空泡茶思考着今天想写些什麽,半夜泡茶的群众着实不少,整个山头上车水马龙,...
今天我们会用部落格跟使用者的关系来讲解关联,首先先做设定,部落格跟使用者的关系为 使用者对应多个部落...
今天要讲的是snapshot函数,顾名思义,snapshot函数能让我们收取程序执行当下的商品资料,...
LogSeverity 有在写Log的人都知道Log需要被分级,而分级对於问题的除错,是很重要的,当...
前言 前面我们介绍C++的使用,有些读者可能会希望使用Python撰写(包括我),因此,我们就来看看...