我一直在尝试模拟使用“用户名”,“全名”或“电子邮件”之一的Instagram登录。
以下是我创建的“帐户” Django应用的文件:
account / urls.py
from django.urls import path
from .views import SignInView, SignUpView
urlpatterns = [
path('signup', SignUpView.as_view()),
path('signin', SignInView.as_view()),
]
account / models.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'
account / views.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全名= Aaron密码= 1234电子邮件[email protected])。但是,我一直在努力找出登录功能出了什么问题。
除了过分地使用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
对象。