我一直在尝试模拟Instagram登录,该登录采用"用户名","全名"或"电子邮件"之一。
以下是我创建的"帐户"Django应用程序的文件:
帐户/网址.py
from django.urls import path
from .views import SignInView, SignUpView
urlpatterns = [
path('signup', SignUpView.as_view()),
path('signin', SignInView.as_view()),
]
帐户/模型.py
from django.db import models
class Account(models.Model):
email = models.CharField(max_length=200)
password = models.CharField(max_length=700)
fullname = models.CharField(max_length=200)
username = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'accounts'
帐户/视图.py
import json
import bcrypt
import jwt
from django.views import View
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from .models import Account
class SignUpView(View):
def post(self, request):
data = json.loads(request.body)
try:
if Account.objects.filter(email=data['email']).exists():
return JsonResponse({"message": "ALREADY EXIST"}, status=409)
hashed_pw = bcrypt.hashpw(data['password'].encode('utf-8'),bcrypt.gensalt()).decode()
Account.objects.create(
email = data['email'],
password = hashed_pw,
fullname = data['fullname'],
username = data['username'],
)
return JsonResponse({"message": "SUCCESS"}, status=200)
except KeyError:
return JsonResponse({"message": "INVALID_KEYS"}, status=400)
class SignInView(View):
def post(self, request):
data = json.loads(request.body)
try:
if Account.objects.filter(Q(email=data['email']) | Q(username=data['username']) | Q(fullname=data['fullname'])).exists():
account = Account.objects.get(Q(email=data['email']) | Q(username=data['username']) | Q(fullname=data['fullname']))
encoded_pw = account.password.encode('utf-8')
encoded_input = data['password'].encode('utf-8')
if bcrypt.checkpw(encoded_input, encoded_pw):
token = jwt.encode({ 'email' : account.email }, 'secret', algorithm='HS256').decode('utf-8')
return JsonResponse({ 'access_token' : token }, status=200)
return HttpResponse(status=403)
return HttpResponse(status=402)
except KeyError:
return JsonResponse({"message": "INVALID_KEYS"}, status=400)
我一直在使用 Httpie 发送 Post 请求,如下所示:
http -v http://127.0.0.1:8000/account/signin username='aaron' password='1234'
但是错误的请求一直出现如下:
Bad Request: /account/signin
[19/May/2020 22:20:33] "POST /account/signin HTTP/1.1" 400 27
我已经在注册方面取得了成功。我通过 Httpie 使用 POST 请求创建了一个帐户(用户名=aaron fullname=Aaron password=1234 email=aaa@aaa.com(。但是,我一直在努力找出登录功能的问题。
除了使用 pdb 和 print(( 之外,我该如何调试它?当错误请求消息出现在终端上时,我什至无法使用 pdb 的 p 方法。
我想问题出在这一行:
if Account.objects.filter(Q(email=data['email']) | Q(username=data['username']) | Q(fullname=data['fullname'])).exists():
这是一个问题,因为除非email
、username
和fullname
存在于data
,否则它都会抛出一个被你捕获的KeyError
并返回一个400
=BadRequest
应对数据使用get(key,default=None)
方法。
然后,只有在键存在时才需要一些逻辑来组合Q
对象。