我一直在尝试模拟 Instagram 登录,它采用“用户名”、“全名”或“电子邮件”之一。
以下是我创建的“帐户”Django 应用程序的文件:
帐户/urls.py
from django.urls import path
from .views import SignInView, SignUpView
urlpatterns = [
path('signup', SignUpView.as_view()),
path('signin', SignInView.as_view()),
]
帐户/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'
帐户/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 电子邮件=aaa@aaa.com)。但是,我一直在努力找出登录功能出了什么问题。
除了积极使用 pdb 和 print() 之外,我该如何进行调试?当 Bad Request 消息出现在终端上时,我什至无法使用 pdb 的 p 方法。