gpt4 book ai didi

python - 使用 Django 登录/注销用户

转载 作者:行者123 更新时间:2023-12-05 08:08:29 25 4
gpt4 key购买 nike

我目前正在使用 Django 开发一个项目。我正在尝试仅使用 python 脚本实现从应用程序登录和注销用户的功能,以便将发布请求从客户端发送到服务器。我正在尝试从我的应用程序中注销用户,但它似乎不起作用。在我的登录功能中,这是用于登录用户的方法:

    # Function for user's login
@csrf_exempt
def loginUser(request):
login_user = authenticate(username=user.customer_username, password=user.customer_password)
if login_user is not None:
if login_user.is_active:
request.session.set_expiry(86400)
login(request, login_user)
print(request.user.is_active)
http_response = HttpResponse()
return http_response

这里打印的结果是True,说明如果我没记错的话登录方式是正确的。当我尝试注销用户时,使用此方法:

    # Function for user's logout
@csrf_exempt
def logoutUser(request):
# Loging out the user
print(request.user.is_active)
logout(request)
http_response = HttpResponse()
return http_response

它没有注销用户,这里打印的结果是 False,这意味着用户没有登录。如果有人知道如何解决这个问题,那将非常有帮助。谢谢。

最佳答案

我设法找到了这个问题的答案。因为我使用 python 脚本在服务器和客户端之间发送和接收 post 请求,由于客户端请求后客户端和服务器之间的连接停止,因此未保存当前登录的用户。因此,通过初始化全局 Session对象,然后使用该对象发出请求,它允许我在请求中保留某些参数。这是我在客户端用来发出请求的代码:

import requests
from requests import Session
# Create the Json object for the login
data = {'username': username,
'password': password}
r = requests.Session()
login_response = r.post("http://127.0.0.1:8000/api/login", data=data)
logout_response = r.post("http://127.0.0.1:8000/api/logout")

这是我在服务器端使用的代码:

# Function for user's login
@csrf_exempt
def loginUser(request):
# Get the username and password from the post request
username = request.POST['username']
password = request.POST['password']
login_user = authenticate(username=username,
password=password)
if login_user is not None:
if login_user.is_active:
login(request, login_user)
http_response = HttpResponse()
return http_response


# Function for user's logout
@csrf_exempt
def logoutUser(request):
# Loging out the user
logout(request)
http_response = HttpResponse()
return http_response

感谢您的帮助!

关于python - 使用 Django 登录/注销用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com