0
我想設計一個簡單的Django「RESTful」API而無需使用django-rest-framework。Django返回JSON與登錄Cookie
終點是/api/login
,它只接受POST方法,在json中只接受username
和password
。我希望它會返回{"status" : 0}
,以便稍後在我的其他端點使用會話cookie。只有當用戶成功登錄後,cookie纔會被設置。
我已經從django.http
導入了JsonResponse
對象,但不太清楚如何爲用戶設置會話。
def login(request):
# some code omitted, like if request.method == "POST"
credential = json.loads(request.body)
username = credential['username']
password = credential['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
auth_login(request, user)
else:
return JsonResponse({"status" : 1, "err" : "Your account has been disabled"})
# TODO: Now return what?
我瀏覽了document,但未能找到任何有用的提示。
與問題無關的建議:爲了防止出現KeyError,在繼續之前,您應該先執行'username = credential.get('username')',然後檢查用戶名是否爲'None'。另外,對密碼也一樣。 – Flux