python - 使用 Requests python 库连接 Django 应用程序时身份验证失败

标签 python django authentication python-requests

也许这里有一个愚蠢的问题: Requests(一个 python HTTP 库)是否支持 Django 1.4?

我使用 Requests 遵循官方快速入门,如下所示:

requests.get('http://127.0.0.1:8000/getAllTracks', auth=('myUser', 'myPass'))

但我从来没有获得正确的身份验证。(当然我已经一次又一次地检查了 url、用户名、密码。)

上面的url'http://127.0.0.1:8000/getAllTracks'匹配了一个Django项目的url.py的url pattern,这个url pattern的回调是'getAllTracks' Django 应用的 View 。

如果我注释掉 'getAllTracks' View 的身份验证代码,那么上面的代码可以正常工作,但是如果我为 View 添加这些身份验证代码,那么上面的代码永远不会通过身份验证对。

View 的认证代码其实很简单,如下(第二行):

def getAllTracks(request):
    if request.user.is_authenticated():
        tracks = Tracks.objects.all()
        if tracks:
            # Do sth. here

这意味着如果我删除上面的第二行(当然有一些缩进调整),那么 requests.get() 操作对我来说是正确的,但如果不是(保留第二行行),那么它永远不会正确。

如有任何帮助,我们将不胜感激。

最佳答案

在 Django 中,身份验证按以下方式工作:

  • 有一个 SessionMiddleware 和 AuthenticationMiddleware。在调用任何 View 之前调用这两个类的 process_request()。
  • SessionMiddleware 在较低级别使用 cookie。它检查名为 sessionid 的 cookie,并尝试将此 cookie 与用户相关联。
  • AuthenticationMiddleware 检查此 cookie 是否与用户关联,然后将 request.user 设置为相应的用户。如果 cookie sessionid 未找到或无法与任何用户相关联,则 request.user 将设置为 AnonymousUser().
  • 由于 Http 是无状态协议(protocol),django 使用这两个中间件并在较低级别使用 cookie 为特定用户维护 session 。

来到代码中,以便请求可以与django一起工作。

您必须首先调用对用户进行身份验证和登录的 View 。此 View 的响应将在 cookie 中包含 sessionid

您应该使用此 cookie 并在下一个请求中发送它,以便 django 可以验证此特定用户并让您的 request.user.is_authenticated() 通过。

from django.contrib.auth import authenticate, login

def login_user(request):
    user = authenticate(username=request.POST.get('username'),  password=request.POST.get('password'))
    if user:
       login(request, user)
       return HttpResponse("Logged In")
    return HttpResponse("Not Logged In")

def getAllTracks(request):
    if request.user.is_authenticated():
        return HttpResponse("Authenticated user")
    return HttpResponse("Non Authenticated user")

发出请求:

import requests

resp = requests.post('http://127.0.0.1:8000/login/', {'username': 'akshar', 'password': 'abc'})

print resp.status_code
200 #output

print resp.content
'Logged In' #output

cookies = dict(sessionid=resp.cookies.get('sessionid'))

print cookies
{'sessionid': '1fe38ea7b22b4d4f8d1b391e1ea816c0'}  #output

response_two = requests.get('http://127.0.0.1:8000/getAllTracks/', cookies=cookies)

请注意,我们使用 cookies 关键字参数传递 cookie

print response_two.status_code
200  #output 

print response_two.content
'Authenticated user'  #output

因此,我们的 request.user.is_authenticated() 正常工作。

response_three = requests.get('http://127.0.0.1:8000/hogwarts/getAllTracks/')

请注意,我们不会在此处传递 cookie。

print response_three.content
'Non Authenticated user' #output

关于python - 使用 Requests python 库连接 Django 应用程序时身份验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10134690/

相关文章:

python - 如何修复此 ' float not iterable ' 错误

python - 带有 python 和 matplotlib 中线条的地理数据图/ map

python - 我应该使用高级 GeoDjango 库进行一项简单的计算吗?

java - 如何使用 Selenium 和 Java 处理浏览器登录弹出窗口

python matplotlib 标签/标题错误字符

python - 如何通过共享内存将 cv::Mat 发送到 python?

python - 如何将 Django 2.2 与旧版 PostgreSQL 8.4 数据库一起使用?

javascript - 有没有办法通过 ajax 提高正常的 Django 表单验证?

java - 如何使用 FreeMarker 通过 Spring Security 成功注销

php - 为什么这个登录表单不起作用?