[英]Django return JSON with Logged in Cookie
我想設計一個簡單的Django“ RESTful” API,而無需使用django-rest-framework。
端點是/api/login
,它僅接受json中帶有username
和password
POST方法。 我希望它返回{"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?
我瀏覽了該文檔,但找不到任何有用的提示。
我進行了測試,我可以只使用return JsonResponse({'status' : 0})
因為cookie是通過authenticate
在Django中注冊的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.